python Events
Events事件
Events是一个简单的同步对象,
事件表示一个内部标志和线程
可以等待设置标志,或设置或清除标志本身。
Events使用
生成event对象
event = threading.Event()
设置标志位
event.set()
清空标志位
event.clear()
等待设置标志位 如果标志位没有设置就一直等待
event.wait()
如果设置了标记,等待方法什么也不做。
如果标记被清除,等待将阻塞,直到它再次被设置。
任何数量的线程都可以等待相同的事件。
标志位被设定,代表绿灯,直接通行。
标志位被清空,代表红灯,wait等待变绿灯。等待标志位在设定。
通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。
import threading import time event = threading.Event() def lighter(): count = 0 event.set() # 变绿灯 while True: if count >5 and count < 10 : #改红灯 event.clear() #清空标志位 print("\033[41;1mred light is on...\033[0m") elif count >10: event.set() # 变绿灯 count = 0 else: print("\033[42;1mgreen light is on...\033[0m") event.set() # 变绿灯 time.sleep(1) count+=1 def car(name): while True: if event.is_set(): #代表绿灯 print("[%s] runing..."% name) time.sleep(1) else: print("[%s] sees red light,waiting..."% name) event.wait() print("[%s] green light is on,start going...") light = threading.Thread(target=lighter,) light.start() car1 = threading.Thread(target=car,args=("Tesla",)) car1.start()
运行结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 green light is on... 2 [Tesla] runing... 3 green light is on... 4 [Tesla] runing... 5 [Tesla] runing... 6 green light is on... 7 [Tesla] runing... 8 green light is on... 9 green light is on... 10 [Tesla] runing... 11 green light is on... 12 [Tesla] runing... 13 [Tesla] runing... 14 red light is on... 15 [Tesla] sees red light,waiting... 16 red light is on... 17 red light is on... 18 red light is on... 19 green light is on... 20 [%s] green light is on,start going... 21 [Tesla] runing... 22 [Tesla] runing... 23 green light is on... 24 [Tesla] runing... 25 green light is on... 26 [Tesla] runing... 27 green light is on... 28 [Tesla] runing... 29 [Tesla] runing... 30 green light is on... 31 green light is on... 32 [Tesla] runing... 33 [Tesla] runing... 34 red light is on... 35 [Tesla] sees red light,waiting...