forked from borafkazanci/CS342-Project3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphil.c
90 lines (74 loc) · 1.57 KB
/
phil.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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <pthread.h>
#define LEFT (pid - 1) % 5
#define RIGHT (pid + 1) % 5
#define EAT 1
#define THINK 2
pthread_t tid[5];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool loop = true;
int phils[5];
int rand1_5(){
return rand() % 5 + 1;
}
int rand1_10(){
return rand() % 10 + 1;
}
void think(int pid){
int time = rand1_10();
sleep(time);
}
void eat(int pid){
printf("philosopher %d started eating now.\n", pid);
int time = rand1_5();
sleep(time);
printf("philosopher %d finished eating now.\n", pid);
}
void hold(int pid){
int left = LEFT;
if (left < 0)
left += 5;
pthread_mutex_lock(&mutex);
while(phils[left] == EAT || phils[RIGHT] == EAT)
pthread_cond_wait(&cond, &mutex);
phils[pid] = EAT;
pthread_mutex_unlock(&mutex);
}
void release(int pid){
pthread_mutex_lock(&mutex);
phils[pid] = THINK;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
static void *philosopher(void* data){
int* i = (int *) &data;
srand(*i);
printf("Phil: %d\n", *i);
while(loop){
think(*i);
hold(*i);
eat(*i);
release(*i);
}
pthread_exit(NULL);
}
int main(){
for(int i = 0; i < 5; i++){
int* pid = (int *) i;
if(pthread_create(&(tid[i]), NULL, philosopher, (int *) pid) != 0){
perror("\n thread creation is failed \n");
exit(-1);
}
}
for(int i = 0; i < 5; i++){
pthread_join(tid[i], NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}