-
Notifications
You must be signed in to change notification settings - Fork 88
/
qlock.c
142 lines (127 loc) · 1.88 KB
/
qlock.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
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 "taskimpl.h"
/*
* locking
*/
static int
_qlock(QLock *l, int block)
{
if(l->owner == nil){
l->owner = taskrunning;
return 1;
}
if(!block)
return 0;
addtask(&l->waiting, taskrunning);
taskstate("qlock");
taskswitch();
if(l->owner != taskrunning){
fprint(2, "qlock: owner=%p self=%p oops\n", l->owner, taskrunning);
abort();
}
return 1;
}
void
qlock(QLock *l)
{
_qlock(l, 1);
}
int
canqlock(QLock *l)
{
return _qlock(l, 0);
}
void
qunlock(QLock *l)
{
Task *ready;
if(l->owner == 0){
fprint(2, "qunlock: owner=0\n");
abort();
}
if((l->owner = ready = l->waiting.head) != nil){
deltask(&l->waiting, ready);
taskready(ready);
}
}
static int
_rlock(RWLock *l, int block)
{
if(l->writer == nil && l->wwaiting.head == nil){
l->readers++;
return 1;
}
if(!block)
return 0;
addtask(&l->rwaiting, taskrunning);
taskstate("rlock");
taskswitch();
return 1;
}
void
rlock(RWLock *l)
{
_rlock(l, 1);
}
int
canrlock(RWLock *l)
{
return _rlock(l, 0);
}
static int
_wlock(RWLock *l, int block)
{
if(l->writer == nil && l->readers == 0){
l->writer = taskrunning;
return 1;
}
if(!block)
return 0;
addtask(&l->wwaiting, taskrunning);
taskstate("wlock");
taskswitch();
return 1;
}
void
wlock(RWLock *l)
{
_wlock(l, 1);
}
int
canwlock(RWLock *l)
{
return _wlock(l, 0);
}
void
runlock(RWLock *l)
{
Task *t;
if(--l->readers == 0 && (t = l->wwaiting.head) != nil){
deltask(&l->wwaiting, t);
l->writer = t;
taskready(t);
}
}
void
wunlock(RWLock *l)
{
Task *t;
if(l->writer == nil){
fprint(2, "wunlock: not locked\n");
abort();
}
l->writer = nil;
if(l->readers != 0){
fprint(2, "wunlock: readers\n");
abort();
}
while((t = l->rwaiting.head) != nil){
deltask(&l->rwaiting, t);
l->readers++;
taskready(t);
}
if(l->readers == 0 && (t = l->wwaiting.head) != nil){
deltask(&l->wwaiting, t);
l->writer = t;
taskready(t);
}
}