from atexit import registerfrom random import randrangefrom threading import BoundedSemaphore, Lock, Threadfrom time import sleep,ctimelock = Lock()MAX = 5 # 最大线程数candytray = BoundedSemaphore(MAX)def refill(): lock.acquire() print('Refilling candy...') try: candytray.release() except ValueError as e: print('full, skipping', e) else: print('ok') lock.release()def buy(): lock.acquire() print('Buying candy...') 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(nloops) print('THECHADY MACHINE (full with %d bars)!' % MAX) Thread(target=consumer, args=(randrange(nloops,nloops+MAX+2),)).start() # buyer Thread(target=producer, args=(nloops,)).start()@registerdef _atexit(): print('all DONE at:', ctime())if __name__ == '__main__': _main()