-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcond-var.py
34 lines (29 loc) · 961 Bytes
/
cond-var.py
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
def Tworker(name, delta):
for _ in range(N):
while heap.mutex == '🔒': # mutex_lock()
sys_sched()
heap.mutex = '🔒'
while not (0 <= heap.count + delta <= 1):
sys_sched()
heap.mutex = '🔓' # cond_wait()
heap.cond.append(name)
while name in heap.cond: # wait
sys_sched()
while heap.mutex == '🔒': # reacquire lock
sys_sched()
heap.mutex = '🔒'
if heap.cond: # cond_signal()
t = sys_choose(heap.cond)
heap.cond.remove(t) # wake up anyone
sys_sched()
heap.count += delta # produce or consume
heap.mutex = '🔓' # mutex_unlock()
sys_sched()
def main():
heap.mutex = '🔓' # 🔓 or 🔒
heap.count = 0 # filled buffer
heap.cond = [] # condition variable's wait list
for i in range(T_p):
sys_spawn(Tworker, f'Tp{i}', 1) # delta=1, producer
for i in range(T_c):
sys_spawn(Tworker, f'Tc{i}', -1) # delta=-1, consumer