Dining philosophers, deadlock example in C POSIX THREADS
I would like to introduce my series of C sandbox stuff. Only for fun, definitely no-production and not clean code :)
I tried to implement dining philosophers problem in perspective of black scenarios. First on the list is deadlock. According to wikipedia "...deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does."
So let's start, here's the sample philosopher code:
After a seconds of execution we have a deadlock situation:
I tried to implement dining philosophers problem in perspective of black scenarios. First on the list is deadlock. According to wikipedia "...deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does."
So let's start, here's the sample philosopher code:
void *philosopher_deadlock(void *p) { struct philosopher_t philosopher = *((struct philosopher_t *) (p)); while (1) { if (!pthread_mutex_lock(&chopstick[philosopher.left])) { printf("%d pick up's left chopstick \n", philosopher.nr); while (1) { if (!pthread_mutex_lock(&chopstick[philosopher.right])) { printf("%d pick up's right chopstick, happy bastard, EAT \n", philosopher.nr); pthread_mutex_unlock(&chopstick[philosopher.left]); pthread_mutex_unlock(&chopstick[philosopher.right]); break; } } } } }
After a seconds of execution we have a deadlock situation:
1 pick up's left chopstick 1 pick up's right chopstick, happy bastard, EAT 1 pick up's left chopstick 1 pick up's right chopstick, happy bastard, EAT 1 pick up's left chopstick 2 pick up's left chopstick 4 pick up's left chopstick 3 pick up's left chopstickFull code here: https://github.com/khipis/c-unix-sandbox/blob/master/philosophers/philosophers_deadlock.c
Komentarze
Prześlij komentarz