在这个 Semaphore 示例中,是否需要锁定 refill() 和 buy() ?
这本书说:当虚拟自动售货机的所有者来向库存中添加一件物品时,执行 refill() 函数。整个例程代表一个关键部分;这就是为什么获取锁是执行所有行的唯一方法。
但我认为没有必要锁定 refill() 和 buy() 你的意见呢?
#!/usr/bin/env python
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()
try:
candytray.release()
except ValueError:
pass
#lock.release()
def buy():
#lock.acquire()
candytray.acquire(False)
#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() # vendor
@register
def _atexit():
print('all DONE at:', ctime())
if __name__ == '__main__':
_main()