0% found this document useful (0 votes)
37 views1 page

Diners

The document describes the dining philosophers problem in which N philosophers share M forks but must acquire both the fork to their left and right to eat. Each philosopher thinks, tries to pick up forks using semaphores to ensure mutual exclusion, eats by setting their state to eating, then puts the forks back and marks their state as thinking. Semaphores and a state array track the philosophers' states to prevent deadlocks.

Uploaded by

dnm99
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views1 page

Diners

The document describes the dining philosophers problem in which N philosophers share M forks but must acquire both the fork to their left and right to eat. Each philosopher thinks, tries to pick up forks using semaphores to ensure mutual exclusion, eats by setting their state to eating, then puts the forks back and marks their state as thinking. Semaphores and a state array track the philosophers' states to prevent deadlocks.

Uploaded by

dnm99
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

THE DINING PHILOSOPHERS

#define N 5 #define LEFT (i-1)%N #define RIGHT (i+1)%N #define THINKING 0 #define HUNGRY 1 #define EATING 2 typedef int semaphore; int state[N]; semaphore mutex = 1; semaphore s[N]; //number of philosophers //number of is left neighbour //number of is right neighbour //philosopher is thinking //philosopher is trying to get forks //philosopher is eating //semaphores are special kind of int //array is to keep track of everyones state //mutual exclusion for critical regions //one semaphore per philosopher

philosopher(i) int i; { while (TRUE) { think(); take_forks(i); eat(); put_forks(i); } } take_forks(i) int i; { down(mutex); state[i] = HUNGRY; test(i); up(mutex); down(s[i]); } put_forks(i) int i; { down(mutex); state[i] = THINKING; test(LEFT); test(RIGHT); up(mutex); } test(i) int i; { state[i] = EATING; up(s[i]); } }

//philosopher number, 0 to N-1 //repeat forever //philosopher is thinking //acquire two forks or block //yum-yum spaghetti //put both forks back on table

//philosopher number 0 to N-1 //enter critical region //record fact that philosopher I is hungry //try to acquire 2 forks //exit critical region //block if forks were not acquired

//philosopher number 0 to N-1 //enter critical region //philosopher has finished eating //see if left neigbour can now eat //see if right neigbour can now eat //exit critical region

//philosopher number 0 to N-1

if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) {

You might also like