forked from schedutron/CPAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
candy.py
62 lines (47 loc) · 1.18 KB
/
candy.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
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
#!/usr/bin/env python3
from atexit import register
from random import randrange
from threading import BoundedSemaphore, Lock, Thread
from time import sleep, ctime
lock = Lock()
MAX = 5
candytray = BoundedSemaphore(MAX)
def refill():
lock.acquire()
print("Refilling candy...", end=" ")
try:
candytray.release()
except ValueError:
print("full, skipping")
else:
print("OK")
lock.release()
def buy():
lock.acquire()
print("Buying candy...", end=" ")
if candytray.acquire(False):
print("OK")
else:
print("empty, skipping")
lock.release()
def producer(loops):
for i in range(loops):
refill()
sleep(randrange(3))
def consumer(loops):
for i in range(loops):
buy()
sleep(randrange(3))
def _main():
print("starting at:", ctime())
nloops = randrange(2, 6)
print("THE CANDY MACHINE (full with %d bars)!" % MAX)
Thread(
target=consumer, args=(randrange(nloops, nloops+MAX+2),)
).start() # buyer
Thread(target=producer, args=(nloops,)).start() # vndr
@register
def _atexit():
print("all done at:", ctime())
if __name__ == "__main__":
_main()