-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDP.c
60 lines (53 loc) · 1.28 KB
/
DP.c
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
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t room;
sem_t chopstick[5];
void *philosopher(void *);
void eat(int);
void eat(int phil){
printf("\nPhilosopher %d is eating",phil);
}
int main() {
int i,a[5];
pthread_t tid[5];
sem_init(&room,0,4);
for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++){
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}
void *philosopher(void *num) {
int phil=*(int *)num;
sem_wait(&room);
printf("\nPhilosopher %d has entered room",phil);
sem_wait(&chopstick[phil]);
sem_wait(&chopstick[(phil+1)%5]);
eat(phil);
sleep(2);
printf("\nPhilosopher %d has finished eating",phil);
sem_post(&chopstick[(phil+1)%5]);
sem_post(&chopstick[phil]);
sem_post(&room);
}
/*Philosopher 0 has entered room
Philosopher 1 has entered room
Philosopher 1 is eating
Philosopher 3 has entered room
Philosopher 3 is eating
Philosopher 2 has entered room
Philosopher 1 has finished eating
Philosopher 3 has finished eating
Philosopher 0 is eating
Philosopher 4 has entered room
Philosopher 2 is eating
Philosopher 0 has finished eating
Philosopher 2 has finished eating
Philosopher 4 is eating
Philosopher 4 has finished eating*/