The signal volume is applicable to multi-threaded competition with limited resources.
1 fromAtexitImportRegister2 fromTimeImportctime, Sleep3 fromThreadingImportThread, Lock, Boundedsemaphore4 fromRandomImportRandrange5 6Lock =Lock ()7MAX = 5#Semaphore size8Candytray =Boundedsemaphore (MAX)9 Ten one defrefull (): a with lock: - Print('refulling ...') - Try: the candytray.release () - exceptvalueerror: - Print('is full!') - Else: + Print('OK') - + defbuy (): a with lock: at Print('Buying ...') - ifCandytray.acquire (False):#Add false parameter, if semaphore is empty, then do not block, but return error, feel similar to Pthread_mutex_trylock in C language - Print('OK') - Else: - Print('Empty') - in defConsumer (loops): - forIinchRange (loops): to refull () +Sleep (randrange (3))#the probability of sleeping longer than creater is as large as possible, - the * defcreater (loops): $ forIinchRange (loops):Panax Notoginseng buy () -Sleep (randrange (5)) the + a defMain (): the Print('starting ...') +n = Randrange (2,6) - Print('the Candy Mechine full with {0}'. Format (MAX)) $Thread (target=creater,args= (randrange (n,n+max+2)) . Start () $Thread (target=consumer, args= (randrange (n,n+max+2)) . Start () - - the @register - defAtexitt ():Wuyi Print('the end!') the - wu if __name__=='__main__': -Main ()
Output result:
Reference: Python core Programming-fourth Chapter Wesley Chun
"[email protected]" semaphore& Candy machine