企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
信号量是另一种同步原语 ### 糖果机 ~~~ #!/usr/bin/env python # encoding: utf-8 # python2 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(): with lock: print 'Refilling candy...', try: candytray.release() except ValueError: print 'full, skipping' else: print 'OK' def buy(): with lock: print 'Buying candy...', # 获取不到时返回False if candytray.acquire(False): print 'OK' else: print 'empty, skipping' def producer(loops): for i in xrange(loops): refill() sleep(randrange(3)) def consumer(loops): for i in xrange(loops): buy() sleep(randrange(3)) def _main(): print 'starting at:', ctime() nloops = randrange(2, 6) print nloops 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() ~~~