Skip to content

Commit 36612d0

Browse files
Merge pull request #3 from PrathamKumar125/PrathamKumar125-patch-4
Create Dining_Philosophers_Problem.c
2 parents 6df83cd + 3636372 commit 36612d0

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#include <stdio.h>
2+
#include <semaphore.h>
3+
#include <pthread.h>
4+
5+
#define N 5
6+
#define THINKING 2
7+
#define HUNGRY 1
8+
#define EATING 0
9+
#define LEFT (phnum + 4)%N
10+
#define RIGHT (phnum + 1)%N
11+
12+
int state[N];
13+
int phil[N] = {0, 1, 2, 3, 4};
14+
15+
sem_t mutex;
16+
sem_t S[N];
17+
18+
void test(int phnum)
19+
{
20+
if (state[phnum] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
21+
{
22+
//state that eating
23+
state[phnum] = EATING;
24+
sleep(2);
25+
printf("Philosopher %d takes fork %d and %d\n", phnum + 1, LEFT + 1, phnum + 1);
26+
printf("Philosopher %d is Eating\n", phnum + 1);
27+
28+
//sem_post(&S[phnum]) has no effect during takefork
29+
//used to wake up hungry philosophers during putfork
30+
sem_post(&S[phnum]);
31+
}
32+
}
33+
34+
//take up chopsticks
35+
void take_fork(int phnum)
36+
{
37+
//access critical section
38+
sem_wait(&mutex);
39+
//state that hungry
40+
state[phnum] = HUNGRY;
41+
printf("Philosopher %d is Hungry\n", phnum + 1);
42+
43+
//eat if neighbours are not eating
44+
test(phnum);
45+
//leave critical section
46+
sem_post(&mutex);
47+
48+
//if unable to eat wait to be signalled
49+
sem_wait(&S[phnum]);
50+
sleep(1);
51+
}
52+
53+
54+
//put down chopsticks
55+
void put_fork(int phnum)
56+
{
57+
//access critical section
58+
sem_wait(&mutex);
59+
// state that thinking
60+
state[phnum] = THINKING;
61+
printf("Philosopher %d putting", phnum + 1);
62+
printf(" fork %d and %d down\n", LEFT + 1, phnum + 1);
63+
printf("Philosopher %d is thinking\n", phnum + 1);
64+
test(LEFT);
65+
test(RIGHT);
66+
//leave critical section
67+
sem_post(&mutex);
68+
}
69+
70+
void *philospher(void *num)
71+
{
72+
while(1)
73+
{
74+
int *i = num;
75+
sleep(1);
76+
take_fork(*i);
77+
sleep(0);
78+
put_fork(*i);
79+
}
80+
}
81+
82+
int main()
83+
{
84+
int i;
85+
pthread_t thread_id[N];
86+
// initialize the semaphores
87+
sem_init(&mutex, 0, 1);
88+
for(i = 0; i < N; i++)
89+
sem_init(&S[i], 0, 0);
90+
for(i = 0; i < N; i++)
91+
{
92+
// create philosopher processes
93+
pthread_create(&thread_id[i], NULL, philospher, &phil[i]);
94+
printf("Philosopher %d is thinking\n", i + 1);
95+
}
96+
for(i = 0; i < N; i++)
97+
pthread_join(thread_id[i], NULL);
98+
return 0;
99+
}

0 commit comments

Comments
 (0)