blob: 7028dbd8b667144579d1b7a92e9f092028aa49fd (
plain)
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
#include "dat.h"
#include "fns.h"
#include "error.h"
void
lock(Lock *l)
{
int i;
if(_tas(&l->val) == 0)
return;
for(i=0; i<100; i++){
if(_tas(&l->val) == 0)
return;
osyield();
}
for(i=1;; i++){
if(_tas(&l->val) == 0)
return;
osmillisleep(i*10);
if(i > 100){
osyield();
i = 1;
}
}
}
int
canlock(Lock *l)
{
return _tas(&l->val) == 0;
}
void
unlock(Lock *l)
{
coherence();
l->val = 0;
}
void
qlock(QLock *q)
{
Proc *p;
lock(&q->use);
if(!q->locked) {
q->locked = 1;
unlock(&q->use);
return;
}
p = q->tail;
if(p == 0)
q->head = up;
else
p->qnext = up;
q->tail = up;
up->qnext = 0;
unlock(&q->use);
osblock();
}
int
canqlock(QLock *q)
{
if(!canlock(&q->use))
return 0;
if(q->locked){
unlock(&q->use);
return 0;
}
q->locked = 1;
unlock(&q->use);
return 1;
}
void
qunlock(QLock *q)
{
Proc *p;
lock(&q->use);
p = q->head;
if(p) {
q->head = p->qnext;
if(q->head == 0)
q->tail = 0;
unlock(&q->use);
osready(p);
return;
}
q->locked = 0;
unlock(&q->use);
}
void
rlock(RWlock *l)
{
qlock(&l->x); /* wait here for writers and exclusion */
lock(&l->l);
l->readers++;
canqlock(&l->k); /* block writers if we are the first reader */
unlock(&l->l);
qunlock(&l->x);
}
/* same as rlock but punts if there are any writers waiting */
int
canrlock(RWlock *l)
{
if (!canqlock(&l->x))
return 0;
lock(&l->l);
l->readers++;
canqlock(&l->k); /* block writers if we are the first reader */
unlock(&l->l);
qunlock(&l->x);
return 1;
}
void
runlock(RWlock *l)
{
lock(&l->l);
if(--l->readers == 0) /* last reader out allows writers */
qunlock(&l->k);
unlock(&l->l);
}
void
wlock(RWlock *l)
{
qlock(&l->x); /* wait here for writers and exclusion */
qlock(&l->k); /* wait here for last reader */
}
void
wunlock(RWlock *l)
{
qunlock(&l->k);
qunlock(&l->x);
}
|