-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_thread_lock_semaphore.py
More file actions
58 lines (45 loc) · 1.23 KB
/
test_thread_lock_semaphore.py
File metadata and controls
58 lines (45 loc) · 1.23 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 了解多线程的锁,信号量
from atexit import register
from random import randrange
import threading
import time
lock = threading.Lock()
MAX = 5
candytray = threading.BoundedSemaphore(MAX)
def refill():
with lock:
print 'Refilling candy...'
try:
candytray.release()
except ValueError:
print 'full,skipping'
else:
print 'ok'
def buy():
with lock:
print 'buying candy...'
if candytray.acquire(False):
print 'ok'
else:
print 'empty,skipping'
def producer(loops):
for i in xrange(loops):
refill()
time.sleep(randrange(3))
def consumer(loops):
for i in xrange(loops):
buy()
time.sleep(randrange(3))
def _main():
print 'starting at:',time.ctime()
nloops = randrange(2,6)
print 'THE CANDY MATCH (full with %d bars)!' % MAX
threading.Thread(target=consumer,args=(randrange(nloops,nloops+MAX+2),)).start()
# threading.Thread(target=producer,args=(nloops,)).start()
@register
def _atexit():
print 'all DOne at:',time.ctime()
if __name__ == '__main__':
_main()