3.2.4 事件
Events
An event is a simple synchronization object;
一个事件就是一个简单的同步对象;
the event represents an internal flag,
事件代表一个内部标记,
and threads can wait for the flag to be set, or set or clear the flag themselves.
并且线程可以等待标记被设定,也可以设定或者清除标记本身。
event = threading.Event()
event.wait()
# a client thread can wait for the flag to be set
一条客户端线程可以等待标记被设定
event.set()
event.clear()
# a server thread can set or reset it
一条服务端线程可以设定或重置标记
If the flag is set, the wait method doesn’t do anything.
如果标记被设定,wait()方法不会做任何事
If the flag is cleared, wait will block until it becomes set again.
如果标记被清除,wait()方法会阻塞直到标记再次被设定
Any number of threads may wait for the same event.
任何数量的线程可以等待相同的事件
通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红
灯停,绿灯行的规则。
下面是红绿灯事件示例
import threading import time event = threading.Event() #事件写法,实例化一个事件 def light(): #红绿灯 count = 0 #设置读秒 event.set() #事件启动 while True: if 5 < count < 11: #6-10秒时红灯亮 print('\033[1;30;41mRed light is counting \033[0m', count) event.clear() #红灯亮时事件结束 elif count > 10: #超出10秒循环结束,计时器归零,事件重新启动 count = 0 event.set() else: #0-5秒绿灯亮,此时事件启动中 print('\033[1;30;42mGreen light is counting \033[0m', count) time.sleep(1) count += 1 def car(name): while True: if event.is_set(): #事件启动时,绿灯亮,可通行 print('\033[1;30;42m%s is passing...\033[0m' % name) time.sleep(1) else: print('\033[1;30;41m%s is waiting...\033[0m' % name) event.wait() #事件等待中,红灯亮 light1 = threading.Thread(target=light, ) light1.start() car1 = threading.Thread(target=car, args=('BMW', )) car1.start()
运行结果