Skip to content

Commit e7f6fbf

Browse files
authored
Update Dining_Philosophore_Semaphore.CPP
1 parent 9f1d250 commit e7f6fbf

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

Dining_Philosophore_Semaphore.CPP

+111
Original file line numberDiff line numberDiff line change
@@ -1 +1,112 @@
1+
#include <stdio.h>
2+
#include <iostream>
3+
#include <pthread.h>
4+
#include <unistd.h>
5+
using namespace std;
16

7+
#define N 10
8+
#define THINKING 2
9+
#define HUNGRY 1
10+
#define EATING 0
11+
#define LEFT (phnum + 4) % N
12+
#define RIGHT (phnum + 1) % N
13+
14+
int phil[N];
15+
int times = 200;
16+
17+
class monitor {
18+
int state[N];
19+
pthread_cond_t phcond[N];
20+
pthread_mutex_t condLock;
21+
22+
public:
23+
void test(int phnum){
24+
if (state[(phnum + 1) % 5] != EATING
25+
and state[(phnum + 4) % 5] != EATING
26+
and state[phnum] == HUNGRY) {
27+
state[phnum] = EATING;
28+
29+
pthread_cond_signal(&phcond[phnum]);
30+
}
31+
}
32+
33+
void take_fork(int phnum){
34+
pthread_mutex_lock(&condLock);
35+
state[phnum] = HUNGRY;
36+
test(phnum);
37+
if (state[phnum] != EATING) {
38+
pthread_cond_wait(&phcond[phnum], &condLock);
39+
}
40+
cout << "Philosopher " << phnum << " is Eating"
41+
<< endl;
42+
43+
pthread_mutex_unlock(&condLock);
44+
}
45+
46+
void put_fork(int phnum){
47+
pthread_mutex_lock(&condLock);
48+
state[phnum] = THINKING;
49+
50+
test(RIGHT);
51+
test(LEFT);
52+
53+
pthread_mutex_unlock(&condLock);
54+
}
55+
56+
monitor(){
57+
for (int i = 0; i < N; i++) {
58+
state[i] = THINKING;
59+
}
60+
61+
for (int i = 0; i < N; i++) {
62+
pthread_cond_init(&phcond[i], NULL);
63+
}
64+
65+
pthread_mutex_init(&condLock, NULL);
66+
}
67+
68+
~monitor(){
69+
for (int i = 0; i < N; i++) {
70+
pthread_cond_destroy(&phcond[i]);
71+
}
72+
73+
pthread_mutex_destroy(&condLock);
74+
}
75+
}
76+
phil_object;
77+
void* philosopher(void* arg){
78+
int c = 0;
79+
while (c < times) {
80+
int i = *(int*)arg;
81+
sleep(1);
82+
phil_object.take_fork(i);
83+
sleep(0.5);
84+
phil_object.put_fork(i);
85+
c++;
86+
}
87+
}
88+
89+
int main(){
90+
pthread_t thread_id[N];
91+
pthread_attr_t attr;
92+
pthread_attr_init(&attr);
93+
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
94+
95+
for (int i = 0; i < N; i++) {
96+
phil[i] = i;
97+
}
98+
99+
for (int i = 0; i < N; i++) {
100+
pthread_create(&thread_id[i], &attr, philosopher, &phil[i]);
101+
cout << "Philosopher " << i + 1 << " is thinking..." << endl;
102+
}
103+
104+
for (int i = 0; i < N; i++) {
105+
pthread_join(thread_id[i], NULL);
106+
}
107+
108+
pthread_attr_destroy(&attr);
109+
pthread_exit(NULL);
110+
111+
return 0;
112+
}

0 commit comments

Comments
 (0)