-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdining_sem.c
More file actions
97 lines (76 loc) · 1.5 KB
/
dining_sem.c
File metadata and controls
97 lines (76 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//Program implementing Dining Philosophers Problem Using Semaphores and Forks
#include<stdio.h>
#include<fcntl.h>
#include<semaphore.h>
#include<sys/wait.h>
#include<pthread.h>
#include<stdlib.h>
sem_t *sem[20];
void philosopher(int val)
{
printf("Philosopher %d Thinking\n",val+1);
while(1)
{
sem_wait(sem[val%5]);
if(!sem_trywait(sem[(val+1)%5]))
break;
else
sem_post(sem[val%5]);
}
printf("\tPhilosopher %d Eating\n",val+1);
sleep(2);
sem_post(sem[val%5]);
sem_post(sem[(val+1)%5]);
printf("\t\tPhilosopher %d Finished Eating\n",val+1);
}
void main()
{
pid_t cpid[5];
char semname[5];
int i=0;
for(i=0;i<5;i++)
{
sprintf(semname,"%d",getpid()+i);
sem[i]=sem_open(semname,O_CREAT|O_EXCL,0666,1);
if(sem[i]==SEM_FAILED)
perror("Unable to create semaphore");
}
for(i=0;i<5;i++)
{
cpid[i]=fork();
if(cpid[i]==0)
break;
}
if(i==5)
{
int status;
for(i=0;i<5;i++)
waitpid(cpid[i],&status,WUNTRACED);
for(i=0;i<5;i++)
{ sem_close(sem[i]);
sprintf(semname,"%d",getpid()+i);
sem_unlink(semname);
}
}
else
philosopher(i);
}
/*
OUTPUT
===============
Philosopher 1 Thinking
Philosopher 2 Thinking
Philosopher 2 Eating
Philosopher 4 Thinking
Philosopher 4 Eating
Philosopher 3 Thinking
Philosopher 5 Thinking
Philosopher 1 Eating
Philosopher 2 Finished Eating
Philosopher 3 Eating
Philosopher 4 Finished Eating
Philosopher 5 Eating
Philosopher 1 Finished Eating
Philosopher 3 Finished Eating
Philosopher 5 Finished Eating
*/