040同步條件event,040同步event

來源:互聯網
上載者:User

040同步條件event,040同步event

 

條件同步和條件變數同步差不多意思,只是少了鎖功能,因為條件同步設計於不訪問共用資源的條件環境,event=threading.Event():條件環境對象,初始值為False.
event.isSet():  返回event的狀態值
event.wait():  如果event.isSet()==False將阻塞線程
event.set():  設定event的狀態值為True,所有阻塞池的線程啟用進入就緒狀態,等待作業系統調度
event.clear():  恢複event的狀態值為False

 1 import time,threading 2  3 class Boss(threading.Thread): 4     def run(self): 5         print('Boss:今晚加班到22:00') 6         event.isSet()or event.set() 7         time.sleep(5) 8         print('Boss:<22:00>可以下班了') 9         event.isSet()orevent.set()10 11 class Worker(threading.Thread):12     def run(self):13         event.wait()14         print('Worker:命苦啊~')15         time.sleep(0.25)16         event.clear()17         event.wait()18         print('Worker:oh,yeah')19 20 if __name__ == '__main__':21     event = threading.Event()22     threads = []23     for i in range(5):24         threads.append(Worker())25     threads.append(Boss())26     for t in threads:27         t.start()28     for t in threads:29         t.join()
View Code
 1 import threading,time 2 import random 3 def light(): 4     if not event.isSet(): 5         event.set() #wait就不阻塞 #綠燈狀態 6     count = 0 7     while True: 8         if count < 10: 9             print('\033[42;1m--green light on---\033[0m')10         elif count <13:11             print('\033[43;1m--yellow light on---\033[0m')12         elif count <20:13             if event.isSet():14                 event.clear()15             print('\033[41;1m--red light on---\033[0m')16         else:17             count = 018             event.set() #開啟綠燈19         time.sleep(1)20         count +=121 def car(n):22     while 1:23         time.sleep(random.randrange(10))24         if  event.isSet(): #綠燈25             print("car [%s] is running.." % n)26         else:27             print("car [%s] is waiting for the red light.." %n)28 if __name__ == '__main__':29     event = threading.Event()30     Light = threading.Thread(target=light)31     Light.start()32     for i in range(3):33         t = threading.Thread(target=car,args=(i,))34         t.start()
View Code

 

來自:http://www.cnblogs.com/yuanchenqi/articles/5733873.html

聯繫我們

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