-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLab-7 - Dining Philosophers using monitors.c
107 lines (100 loc) · 1.43 KB
/
Lab-7 - Dining Philosophers using monitors.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include <semaphore.h>
#include "monitor.h"
sem_t mutex;
sem_t next;
int next_count = 0;
typedef struct
{
sem_t sem;
int count;
}condition;
condition x[N];
int state[N];
int turn[N];
void wait(int i)
{
x[i].count++;
if(next_count > 0)
{
sem_post(&next);
}
else
{
sem_post(&mutex);
}
sem_wait(&x[i].sem);
x[i].count--;
}
void signal(int i)
{
if(x[i].count > 0)
{
next_count++;
sem_post(&x[i].sem);
sem_wait(&next);
next_count--;
}
}
void test(int i)
{
if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING && turn[i] == i && turn[LEFT] == i)
{
state[i] = EATING;
signal(i);
}
}
void take_chopsticks(int i)
{
sem_wait(&mutex);
state[i] = HUNGRY;
test(i);
while(state[i] == HUNGRY)
{
wait(i);
}
if(next_count > 0)
{
sem_post(&next);
}
else
{
sem_post(&mutex);
}
}
void put_chopsticks(int i)
{
sem_wait(&mutex);
state[i] = THINKING;
turn[i] = RIGHT;
turn[LEFT] = LEFT;
test(LEFT);
test(RIGHT);
if(next_count > 0)
{
sem_post(&next);
}
else
{
sem_post(&mutex);
}
}
void initialization()
{
int i;
sem_init(&mutex,0,1);
sem_init(&next,0,0);
for(i = 0;i < N;i++)
{
state[i] = THINKING;
sem_init(&x[i].sem,0,0);
x[i].count = 0;
turn[i] = i;
}
turn[1] = 2;
turn[3] = 4;
turn[6] = 0;
}