"python@thread" semaphore& Candy Machine

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.