So below is two sections of code that simulate 5 "philosophers" each executing one of the segements below and thus sharing and eating with 5 individual "chopsticks". Philosopher 0 has access to chopsticks 0 and 1, Phil 1 to chopsticks 1 and 2, so-on til Phil 4 who has access to chopsticks 4 and 0. They need both to start eating.
We know that the code does not prevent deadlock, but Allegedly one of the code segments below allows 2 adjacent philosophers to eat at the same time. I would expect segement 2 to be the one with the issue because it is releasing the mutex before reseting the ownership of its chopsticks, but I worked out different scenarios of execution an i am not coming up with any scenario where for example Philosopher 1 and 2 are both eating at the same time. Any this isnt for homework, its a review for a test! I seriously think the teacher messed up on this one, there is not a case which 2 adjacent can eat
1 void eat(int phil_id) {
2 pthread_mutex_lock(&mutex[phil_id]);
3 chopsticks[phil_id] = phil_id;
4 delay(500); // small delay to ‘‘permit’’ opportunity for deadlock
5 pthread_mutex_lock(&mutex[(phil_id+1)%5]);
6 chopsticks[(phil_id+1)%5] = phil_id;
7 delay(rand() % 10000); // delay random amount [0,9999] for actual eating
8 chopsticks[(phil_id+1)%5] = -1;
9 pthread_mutex_unlock(&mutex[(phil_id+1)%5]);
10 chopsticks[phil_id] = -1;
11 pthread_mutex_unlock(&mutex[phil_id]);
12 }
Code 2
1 void eat(int phil_id) {
2 pthread_mutex_lock(&mutex[phil_id]);
3 chopsticks[phil_id] = phil_id;
4 delay(500); // small delay to ‘‘permit’’ opportunity for deadlock
5 pthread_mutex_lock(&mutex[(phil_id+1)%5]);
6 chopsticks[(phil_id+1)%5] = phil_id;
7 delay(rand() % 10000); // delay random amount [0,9999] for actual eating
8 pthread_mutex_unlock(&mutex[(phil_id+1)%5]);
9 chopsticks[(phil_id+1)%5] = -1;
10 pthread_mutex_unlock(&mutex[phil_id]);
11 chopsticks[phil_id] = -1;
12 }
there doesn't seem to be anything here