040 synchronization condition event

Condition synchronization and condition variable synchronization have the same meaning, but less lock function, because condition synchronization is designed in the condition environment without access to shared resources, event=threading.Event(): condition environment object, initial value is False
event.isSet(): returns the status value of event
event.wait(): if event.isSet()==False, the thread will be blocked
event.set(): set the state value of event to True, and all threads in the blocking pool will be activated and ready for operation system scheduling
event.clear(): the state value of recovery event is False

 1 import time,threading
 2 
 3 class Boss(threading.Thread):
 4     def run(self):
 5         print('Boss:Work overtime till 22:00 tonight')
 6         event.isSet()or event.set()
 7         time.sleep(5)
 8         print('Boss:<22:00>It's time to get off work')
 9         event.isSet()orevent.set()
10 
11 class Worker(threading.Thread):
12     def run(self):
13         event.wait()
14         print('Worker:Miserable life~')
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()
 1 import threading,time
 2 import random
 3 def light():
 4     if not event.isSet():
 5         event.set() #wait No obstruction. #Green light status
 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 = 0
18             event.set() #Turn on the green light.
19         time.sleep(1)
20         count +=1
21 def car(n):
22     while 1:
23         time.sleep(random.randrange(10))
24         if  event.isSet(): #green light
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()

 

From: http://www.cnblogs.com/yunchenqi/articles/5733873.html

Tags: Python less

Posted on Fri, 03 Apr 2020 18:09:58 -0700 by intergroove