Question: Compile and run dine2.cpp with ^C . What is the maximum number of philosopers who can eat simultaneously? Add a delay statement like SDL_Delay (
| Compile and run dine2.cpp with ^C. What is the maximum number of philosopers who can eat simultaneously? Add a delay statement like SDL_Delay ( rand() % 2000 ); right after the take_chops( l ) statement in the philosoper() function. Run the program for a longer time. What do you observe? You should have observed deadlock in running dine2. To avoid deadlock, you can use an array state to record the state of each philosopher, and one can pick up the chopsticks only if her neighbours are not eating. Implement this mechanism and call program dine3.cpp. Repeat the above experiment to see whether dedlock occurs and what the maximum number of philosophers can dine simultaneously. /* dine2.cpp : mutexes lock chopsticks Compile: g++ -o dine2 dine2.cpp -lSDL Execute: ./dine2 */ #include |
Your progam may have code segments similar to the following:
#define LEFT (i - 1) % 5 #define RIGHT (i + 1) % 5 #define HUNGRY 0 #define EATING 1 #define THINKING 2 SDL_sem *s[5]; // one semaphore per philosopher bool quit = false; int nEating = 0; // number of philosopers eating SDL_mutex *mutex; int state[5]; //array keeping track of everyone's state void test ( int i ) { if ( state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING ) { state[i] = EATING; SDL_SemPost ( s[i] ); } } void putdown ( int i ) { SDL_LockMutex ( mutex ); state[i] = THINKING; test ( LEFT ); test ( RIGHT ); SDL_UnlockMutex ( mutex ); } ....... |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
