python 線程之threading(五)

來源:互聯網
上載者:User

標籤:imp   學習   計數   sem   target   targe   通知   rgs   event   

在學習了Event和Condition兩個線程同步工具之後還有一個我認為比較雞肋的工具 semaphores 

1. 使用semaphores的使用效果和Condition的notify方法的效果基本相同。每次只能通知一個阻塞線程繼續運行

2. 訊號量同步基於內部計數器,每調用一次acquire(),計數器減1;每調用一次release(),計數器加1.當計數器為0時,acquire()調用被阻塞

 1 import threading 2 import time 3  4 def countdown(n, sema): 5     while n > 0: 6         n -= 1 7         sema.acquire() 8         print(‘current countdown:‘,n) 9             10 11 def countup(n, sema):12     while n < 100:13         n += 114         sema.acquire()15         print(‘current countup:‘,n)16 17 sema = threading.Semaphore()18 threading.Thread(target=countdown,args=(100, sema)).start()19 threading.Thread(target=countup,args=(0, sema)).start()20 for i in range(100):21     sema.release()22     time.sleep(3)

 

python 線程之threading(五)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.