/
philo.c
73 lines (60 loc) · 1.18 KB
/
philo.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
#include <minix/callnr.h>
#include <minix/com.h>
#include <minix/config.h>
#include <minix/ipc.h>
#include <minix/endpoint.h>
#include <minix/sysutil.h>
#include <minix/const.h>
#include <minix/type.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
// down = synchronous
void sem_down(endpoint_t e)
{
message m;
int r;
m.m_type = SEM_DOWN;
// sendrec(SEMA_PROC_NR, &m)
r = sendrec(e, &m);
if (r)
printf("semaphore down error\n");
}
// up not synchronous
void sem_up(endpoint_t e)
{
message m;
int r;
m.m_type = SEM_UP;
r = sendnb(e, &m);
if (r)
printf("semaphore up error\n");
}
int main(int argc, char *argv[])
{
endpoint_t who;
if (argc != 3) {
fprintf(stderr, "Usage: %s <name> <endpoint>\n", argv[0]);
return -1;
}
who = atoi(argv[2]);
while (1) {
/* take a fork */
sem_down(who);
/* take another fork */
sem_down(who);
printf("[%s] is eating...\n", argv[1]);
sleep(5);
/* put down two forks */
sem_up(who);
sem_up(who);
/* the philosopher often thinks too hard
* and gets hungry easily, so he needs to
* eat again in a short time. :-)
*/
printf("[%s] is thinking...\n", argv[1]);
sleep(15);
}
return 0;
}