Question: Problem 2 : In lecture 7 , we have described the solution to Dining - Philosophers Problem that avoid the deadlock in C . Complete
Problem : In lecture we have described the solution to DiningPhilosophers Problem that avoid the deadlock in C Complete the following code that uses semaphore.
#include
#include
#include
#define N
#define THINKING
#define HUNGRY
#define EATING
#define LEFT phnum N
#define RIGHT phnum N
int stateN;
int philN;
semt mutex;
semt SN;
void testint phnum
if statephnum HUNGRY
&& stateLEFT EATING
&& stateRIGHT EATING
state that eating
statephnum EATING;
sleep;
printfPhilosopher d takes fork d and d
phnum LEFT phnum ;
printfPhilosopher d is Eating
phnum ;
sempost&Sphnum;
take up chopsticks
void takeforkint phnum
TODO: use semaphore wait
state that hungry
statephnum HUNGRY;
printfPhilosopher d is Hungry
phnum ;
eat if neighbours are not eating
testphnum;
TODO : use semaphore post
if unable to eat wait to be signalled
semwait&Sphnum; Noting to do here
sleep;
put down chopsticks
void putforkint phnum
TODO: use semaphore wait
state that thinking
statephnum THINKING;
printfPhilosopher d putting fork d and d down
phnum LEFT phnum ;
printfPhilosopher d is thinking
phnum ;
testLEFT;
testRIGHT;
TODO : use semaphore post
void philosophervoid num
while
int i num;
sleep;
takeforki;
sleep;
putforki;
int main
int i;
pthreadt threadidN;
initialize the semaphores
seminit&mutex, ;
for i ; i N; i
seminit&Si;
for i ; i N; i
create philosopher processes
pthreadcreate&threadidi NULL,
philosopher, &phili;
printfPhilosopher d is thinking
i ;
for i ; i N; i
pthreadjointhreadidi NULL;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
