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...') 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() @register def _atexit(): print('all DONE at:', ctime()) if __name__ == '__main__': _main()