Skip to content
Snippets Groups Projects
Commit 7e028c8c authored by Mactavish's avatar Mactavish
Browse files

add deadlock exercise

parent 61d303dc
Branches
Tags
No related merge requests found
PROG = simple_deadlock
OBJECTS = simple_deadlock.o
CC = gcc
CFLAGS = -Wall -std=c11 -pthread
CFLAGS += -I. # add the current directory to the include path
.Phone: all
all: clean $(PROG) # build and run the program
./$(PROG)
$(PROG): $(OBJECTS) # link the object files into a binary
$(CC) $(CFLAGS) $^ -o $@
$(OBJECTS): %.o: %.c # compile the source files into object files
$(CC) $(CFLAGS) -c $<
.PHONY: clean
clean: # remove the object files and the binary
rm -f $(OBJECTS) $(PROG)
# Simple deadlock
Here is a small exercise that helps you understand common deadlock situation in C.
## Instructions
Read through the source code in `simple_deadlock.c`, try to run it multiple times.
Then fix the code that causes the deadlock. Recompile it and run it again.
## Build
```bash
# build and run the executable
make
# clean all compilation files
make clean
```
#include <pthread.h>
#include <stdio.h>
const int SIZE = 10;
pthread_mutex_t g_mutex, even_mutex, odd_mutex;
void shared_print_thread_even(int i) {
pthread_mutex_lock(&even_mutex);
pthread_mutex_lock(&odd_mutex);
printf(" %d ", i);
pthread_mutex_unlock(&odd_mutex);
pthread_mutex_unlock(&even_mutex);
}
void shared_print_thread_odd(int i) {
pthread_mutex_lock(&odd_mutex);
pthread_mutex_lock(&even_mutex);
printf(" %d ", i);
pthread_mutex_unlock(&even_mutex);
pthread_mutex_unlock(&odd_mutex);
}
void shared_print_main(int i) {
pthread_mutex_lock(&g_mutex);
printf(" %d ", i);
pthread_mutex_unlock(&g_mutex);
}
void *f(void *arg) {
int n = *(int *)arg;
for (int i = SIZE * (n - 1); i < SIZE * n; i++) {
if (n % 2 == 0)
shared_print_thread_even(i);
else
shared_print_thread_odd(i);
}
return NULL;
}
int main() {
pthread_t t1, t2, t3, t4, t5;
// Initialize the mutexes
pthread_mutex_init(&g_mutex, NULL);
pthread_mutex_init(&even_mutex, NULL);
pthread_mutex_init(&odd_mutex, NULL);
int t1_arg = 1, t2_arg = 2, t3_arg = 3, t4_arg = 4, t5_arg = 5;
// Create the threads
pthread_create(&t1, NULL, f, &t1_arg);
pthread_create(&t2, NULL, f, &t2_arg);
pthread_create(&t3, NULL, f, &t3_arg);
pthread_create(&t4, NULL, f, &t4_arg);
pthread_create(&t5, NULL, f, &t5_arg);
for (int i = -1; i > -SIZE; i--)
shared_print_main(i);
// Wait for the threads to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
pthread_join(t5, NULL);
// Destroy the mutexes
pthread_mutex_destroy(&g_mutex);
pthread_mutex_destroy(&even_mutex);
pthread_mutex_destroy(&odd_mutex);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment