python 線程之 threading(四)

來源:互聯網
上載者:User

標籤:python   self   print   release   事件   blank   imp   狀態   喚醒   

python 線程之 threading(三) http://www.cnblogs.com/someoneHan/p/6213100.html中對Event做了簡單的介紹。

但是如果線程打算一遍一遍的週期性通知某個事件。應該使用Condition

1. 使用Condition首先應該擷取Condition即使Condition進入鎖的狀態

2. 線上程執行過程中需要等待其他線程通知,然後才開始向下啟動並執行地方使用Condition.wait()方法,線程進入阻塞狀態。

3. 使用Condition對鎖進行release().

4. 如果Condition通知所有的等待線程繼續運行可以使用notify_all()方法,如果只是喚醒其中的一個線程使用notify方法

 1 import threading 2 import time 3  4  5 class CountDown(threading.Thread): 6     def __init__(self, startNum, condition): 7         self.condition = condition 8         self.startNum = startNum 9         threading.Thread.__init__(self)10 11     def run(self):12         while self.startNum > 0:13             with self.condition:14                 self.startNum -= 115                 print(‘countdown current num :‘, self.startNum)16                 self.condition.wait()17 18 19 class CountUp(threading.Thread):20     def __init__(self, startNum, condition):21         self.condition = condition22         self.startNum = startNum23         threading.Thread.__init__(self)24 25     def run(self):26         while self.startNum < 100:27             with self.condition:28                 self.startNum += 129                 print(‘countup current num:‘, self.startNum)30                 self.condition.wait()31 32 condition = threading.Condition()33 countdown = CountDown(100, condition)34 countdown.start()35 countup = CountUp(0, condition)36 countup.start()37 for i in range(100):38     with condition:39         print(‘notify‘)40         condition.notify_all()#如果只通知一個線程繼續運行使用 condition.notify()41     time.sleep(1)

 

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.