-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patht3.c
79 lines (66 loc) · 1.51 KB
/
t3.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
/*
* Test Program #3 - Semaphore
*/
#include <stdio.h>
#include <stdlib.h>
#include "ud_thread.h"
sem_t *s;
int resource = 0;
void read_function(int val)
{
long i;
int res_before, res_after;
for (i = 0; i < 5; i++)
{
printf("I am READ thread %d (%ld)\n", val, i);
sem_wait(s);
res_before = resource;
printf(" [%d READ %ld] resource = %d\n", val, i, resource);
t_yield();
printf(" ** [%d READ %ld] returns from t_yield()\n", val, i);
res_after = resource;
if (res_before != res_after)
{
fprintf(stderr, "[THREAD %d] error in the semaphore program \n", val);
exit(-1);
}
sem_signal(s);
}
t_terminate();
}
void write_function(int val)
{
long i;
for (i = 0; i < 5; i++)
{
printf("I am WRITE thread %d (%ld)\n", val, i);
sem_wait(s);
resource = rand() % 100;
printf(" [%d WRITE %ld] resource = %d\n", val, i, resource);
sem_signal(s);
t_yield();
}
t_terminate();
}
int main(void)
{
int i;
t_init();
sem_init(&s, 1);
t_create(write_function, 1, 1);
t_create(write_function, 2, 1);
t_create(read_function, 11, 1);
t_create(read_function, 22, 1);
t_create(write_function, 3, 1);
t_create(write_function, 4, 1);
t_create(read_function, 33, 1);
t_create(read_function, 44, 1);
for (i = 0; i < 60; i++)
{
printf("I am main thread (%d)...\n", i);
t_yield();
}
sem_destroy(&s);
t_shutdown();
return 0;
}