Event: 用于线程之间状态的同步。对全局变量不断地做修改。
Event=threading.Event() #生成1个event的对象
Event.wait() #等着设定全局变量。检测标志位是否有设置,如果标志位没有设置的话,会一直卡在这里。等待标志位被设定。
如果标志位被设定了,代表绿灯,直接通行。wait不阻塞。
如果标志位被清空,代表红灯,wait等待。
多个线程可以等待同一个event的标志位的变化。
Event.set() #设置一个标志位,相当于全局变量
Event.clear() #清空标志位
Event.is_set() #判断是否设置了标志位
理解点:
1.车的线程与红绿灯的线程之间有了关联,车的线程会根据红绿灯的线程而变化。
2.每一次状态的切换,就是一次事件的发生,会相应地做不同的事情。
import time,threading event=threading.Event() def lighter():
count=0
event.set() #先设为绿灯
while True:
if count>5 and count<10: #改成红灯
event.clear() #清空标志位,在红灯状态卡10s
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')
time.sleep(1)
count+=1 def car(name):
while True:
if event.is_set(): #设置了标志位,代表绿灯
print('[%s] running...'%name)
time.sleep(1)
else:
print('[%s] red light,waiting..'%name)
event.wait()
print('[%s] green is on, start going.'%name ) light=threading.Thread(target=lighter,)
light.start()
car1=threading.Thread(target=car,args=('Tesla',))
car1.start()
运行结果:
green light is on..
[Tesla] running...
green light is on..
[Tesla] running...
green light is on..
[Tesla] running...
[Tesla] running...
green light is on..
[Tesla] running...
green light is on..
[Tesla] running...
green light is on..
[Tesla] running...
red light is on..
red light is on..
[Tesla] red light,waiting..
red light is on..
red light is on..
green light is on..
[Tesla] green is on, start going.
[Tesla] running...
green light is on..
[Tesla] running...