-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdining_philosopher.c
More file actions
52 lines (37 loc) · 1.05 KB
/
Copy pathdining_philosopher.c
File metadata and controls
52 lines (37 loc) · 1.05 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
// 3. Dining Philosophers Problem
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define N 5
sem_t chopsticks[N];
void *philosopher(void *arg) {
int id = *(int *)arg;
while (1) {
printf("Philosopher %d is thinking...\n", id);
sleep(rand() % 3);
sem_wait(&chopsticks[id]);
sem_wait(&chopsticks[(id + 1) % N]);
printf("Philosopher %d is eating...\n", id);
sleep(rand() % 2);
sem_post(&chopsticks[id]);
sem_post(&chopsticks[(id + 1) % N]);
}
return NULL;
}
int main() {
pthread_t philosophers[N];
int id[N];
for (int i = 0; i < N; i++)
sem_init(&chopsticks[i], 0, 1);
for (int i = 0; i < N; i++) {
id[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &id[i]);
}
for (int i = 0; i < N; i++)
pthread_join(philosophers[i], NULL);
for (int i = 0; i < N; i++)
sem_destroy(&chopsticks[i]);
return 0;
}