-
Notifications
You must be signed in to change notification settings - Fork 0
/
dining_main.c
76 lines (52 loc) · 1.44 KB
/
dining_main.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
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <inttypes.h>
/* NO NEED TO MODIFY */
#define SERVINGS 100000
#include "philosopher.h"
#include "chopsticks.h"
#include "gtthread.h"
static double const thinking_to_eating = 0.02;
static double const eating_to_thinking = 0.05;
static unsigned int seed[5];
static void eat(int phil_id){
start_eating(phil_id);
while ( (rand_r(&seed[phil_id]) / (RAND_MAX + 1.0)) >= eating_to_thinking);
stop_eating(phil_id);
}
static void think(int phil_id){
while ((rand_r(&seed[phil_id]) / (RAND_MAX + 1.0)) >= thinking_to_eating);
}
static int servings = SERVINGS;
static void* philosodine(void* arg){
intptr_t phil_id;
phil_id = (intptr_t) arg;
seed[phil_id] = phil_id+1;
while(0 < __sync_fetch_and_sub(&servings, 1L)){
/* Philosopher was just served */
/* Picks up his chopsticks */
pickup_chopsticks(phil_id);
/* Eats */
eat(phil_id);
/* Puts down his chopsticks */
putdown_chopsticks(phil_id);
/* And then thinks. */
think(phil_id);
}
return NULL;
}
int main(){
long i;
gtthread_t phil_threads[5];
gtthread_init(500);
chopsticks_init();
for(i = 0; i < 5; i++)
gtthread_create(&phil_threads[i], philosodine, (void*) i);
for(i = 0; i < 5; i++)
gtthread_join(phil_threads[i], NULL);
chopsticks_destroy();
for(i = 0; i < 5; i++)
printf("Philosopher %ld ate %d meals.\n", i, count_meals_eaten(i));
return 0;
}