【Python@Thread】Semaphore&糖果機

來源:互聯網
上載者:User

標籤:cti   can   else   機率   create   pytho   dom   http   name   

訊號量適用與多線程競爭有限資源的情況。

 1 from atexit import register 2 from time import ctime, sleep 3 from threading import Thread, Lock, BoundedSemaphore 4 from random import randrange 5  6 lock = Lock() 7 MAX = 5                             #訊號量大小 8 candytray = BoundedSemaphore(MAX) 9 10 11 def refull():12     with lock:13         print(‘refulling...‘)14         try:15             candytray.release()16         except ValueError:17             print(‘Is Full!‘)18         else:19             print(‘OK‘)20 21 def buy():22     with lock:23         print(‘buying...‘)24         if candytray.acquire(False):    #加入False參數,如果訊號量為空白,則不阻塞,而是返回錯誤,感覺類似與C語言中的pthread_mutex_trylock25             print(‘OK‘)26         else:27             print(‘empty‘)28 29 def consumer(loops):30     for i in range(loops):31         refull()32         sleep(randrange(3))             #睡眠時間盡量長於creater的機率盡量大,33 34 35 def creater(loops):36     for i in range(loops):37         buy()38         sleep(randrange(5))39 40 41 def main():42     print(‘starting...‘)43     n = randrange(2,6)44     print(‘the candy mechine full with {0}‘.format(MAX))45     Thread(target=creater,args=(randrange(n,n+MAX+2),)).start()46     Thread(target=consumer, args=(randrange(n,n+MAX+2),)).start()47 48 49 @register50 def atexitt():51     print(‘The end!‘)52 53 54 if __name__ == ‘__main__‘:55     main()

輸出結果:

參考資料:Python核心編程.第四章.Wesley Chun著

 

【[email protected]】Semaphore&糖果機

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.