-
事件(event)
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 flags themselvesevent = threading.event()
A client thread can wait for the flag to be set
event.wait()
A server thread can set or reset it
event.set()
event.clear()
If the flag is set, the wait method doesn’t do anything.
If the flag is clear, wait will block until it becomes set again.
Any number of threads may wait for the same event.
通过event来实现线程之间的交互redlight = False
while True:
if counter > 30:
redlight = True
if counter >50:
redlight = False
counter = 0
下面以一个红绿灯的程序作为例子来理解一下事件:
# Author : Xuefeng
import threading, time
# 实例化事件
event = threading.Event()
def light():
'''
定义灯的函数,红灯亮5秒绿灯亮5秒。
:return:
'''
count = 0
# 事件置位
event.set()
while True:
if count > 5 and count < 10: # Change for red light
event.clear() # clear the flag
print("\033[41;1m red light is on...\033[0m")
elif count > 10:
event.set() # set the flag
count = 0
else:
print("\033[42;1m green light is on...\033[0m")
time.sleep(1)
count += 1
def car(name):
'''
定义汽车模型,红灯停,绿灯行
:param name: 汽车的名字
:return:
'''
while True:
if event.is_set(): # Green light
print("[%s] running..." % name)
time.sleep(1)
else:
print("[%s] sees red light, waitting..." %name)
event.wait()
print("\033[42;1m Green light on, [%s] startting...\033[0m" %name)
# 创建灯的线程
Light = threading.Thread(target=light)
Light.start()
# 创建3个小汽车
Car_1 = threading.Thread(target=car, args=("Tom",))
Car_2 = threading.Thread(target=car, args=("Jim",))
Car_3 = threading.Thread(target=car, args=("Mary",))
Car_1.start()
Car_2.start()
Car_3.start()