-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab4_x0.c
114 lines (92 loc) · 1.5 KB
/
lab4_x0.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "3140_concur.h"
#include "utils.h"
#include "lock.h"
#include "cond.h"
lock_t l;
cond_t cr;
cond_t cw;
unsigned int nr= 0;
unsigned int nw= 0;
void p1 (){
int i;
for (i=0; i < 10; i++) {
delay();
LEDBlue_Toggle();
}
}
void reader (void) {
l_lock(&l);
if(nw!=0){
c_wait(&l,&cr);
}
nr++;
if(c_waiting(&l,&cr)){
c_signal(&l,&cr);
}
else{
l_unlock(&l);
}
/*start reading*/
p1();
/*end reading*/
l_lock(&l);
nr--;
if(c_waiting(&l,&cw) && nr == 0){
c_signal(&l,&cw);
}
else if(c_waiting(&l,&cr)){
c_signal(&l,&cr);
}
else{
l_unlock(&l);
}
}
void writer (void) {
l_lock(&l);
if(nw!=0 || nr!=0){
c_wait(&l,&cw);
}
nw++;
l_unlock(&l);
/*start writing*/
LEDRed_Toggle();
delay();
LEDRed_Toggle();
delay();
l_lock(&l);
nw--;
if(c_waiting(&l,&cw) && nr == 0){
c_signal(&l,&cw);
}
else if(c_waiting(&l,&cr)){
c_signal(&l,&cr);
}
else{
l_unlock(&l);
}
}
int main (void){
LED_Initialize();
l_init (&l);
c_init (&l,&cr);
c_init (&l,&cw);
if (process_create (writer,20) < 0) {
return -1;
}
if (process_create (reader,20) < 0) {
return -1;
}
if (process_create (reader,20) < 0) {
return -1;
}
if (process_create (reader,20) < 0) {
return -1;
}
if (process_create (writer,20) < 0) {
return -1;
}
process_start();
LEDGreen_On();
while (1) ;
return 0;
}