用 multiprocessing.Event 实现线程间通讯,使用multiprocessing.Event能够使一个线程等待其余线程的通知,
咱们把这个Event传递到线程对象中;主要用于主线程控制其余线程的执行,事件主要提供了三个方法:wait、clear、set。
事件处理的机制:
全局定义了一个Flag; 若是Flag值为False(clear:将Flag设置为False),则执行event.wait方法时阻塞; 若是Flag值为True(set:将Flag设置为True),则执行event.wait方法时不阻塞。 注: event对象默认为False,即遇到event对象在等待就阻塞线程的执行。
from multiprocessing import Event e=Event() # <multiprocessing.synchronize.Event object at 0x0000019295AA8400> 建立对象 print(e.is_set()) # False 查看 状态 e.set() # 改变状态Event默认是状态是false print(e.is_set()) # True e.wait() # wait有一个阻塞效果 # 在以前必须改变Event默认状态 才会执行wait以后的代码 print(1111111111) 执行结果 False True 1111111111
e=Event() print(e.is_set()) # 查看状态 e.wait() # 被阻塞了 由于Event默认是False 要开起后才会执行wait以后的代码 print("11111111") # 不会打印出来 # 执行结果 False wait1 True
# wait(time)中的time参数能够设置时间,当超过time时间后便可阻断阻塞 e=Event() print(e.is_set()) # 查看状态 e.wait(3) # 被阻塞了 由于Event默认是False 里面设置时间 print("11111111") # 也会打印 # 执行结果 False 11111111
from multiprocessing import Event if __name__ == '__main__': e = Event() print(e.is_set()) #False # e.wait() <-会阻塞在此处 e.clear() #clear在wait后面,并不能生效。 print('wait1') e.set() print(e.is_set()) #True e.clear() e.wait() #不会阻塞 print('wait2')
False
wait1
Truepython
红绿等 import random import time from multiprocessing import Process, Event def cars(event, i ): if not event.is_set(): print('cat: %s 等待红灯' %i) event.wait() #阻塞直到事件状态变为 True的信号 else: print('\033[0;32;40mcar%i经过\033[0m'%i) def light(event): while True: if event.is_set(): event.clear() print('\033[31m红灯亮了\033[0m') else: event.set() print('\033[32m绿灯亮了\033[0m') time.sleep(2) if __name__ == '__main__': event = Event() p = Process(target=light, args=(event,)) p.start() for i in range(20): car = Process(target= cars, args=(event, i )) car.start() time.sleep(random.random())