python 线程间事件通知
这是线程间最简单的通信机制:一个线程发送事件,其他线程等待事件
事件机制使用一个内部的标志,使用set方法进行使能为True,使用clear清除为false
wait方法将会阻塞当前线程知道标记为True
1 import queue 2 from random import randint 3 from threading import Thread 4 from threading import Event 5 6 class WriteThread(Thread): 7 def __init__(self,queue,WEvent,REvent): 8 Thread.__init__(self) 9 self.queue = queue 10 self.REvent = REvent 11 self.WEvent = WEvent 12 13 def run(self): 14 data = [randint(1,10) for _ in range(0,5)] 15 self.queue.put(data) 16 print("send Read Event") 17 self.REvent.set() #--> 通知读线程可以读了 18 self.WEvent.wait() #--> 等待写事件 19 print("recv write Event") 20 self.WEvent.clear() #-->清除写事件,以方便下次读取 21 22 class ReadThread(Thread): 23 def __init__(self,queue,WEvent, REvent): 24 Thread.__init__(self) 25 self.queue = queue 26 self.REvent = REvent 27 self.WEvent = WEvent 28 def run(self): 29 while True: 30 self.REvent.wait() #--> 等待读事件 31 print("recv Read Event") 32 data = self.queue.get() 33 print("read data is {0}".format(data)) 34 print("Send Write Event") 35 self.WEvent.set() #--> 发送写事件 36 self.REvent.clear() #--> 清除读事件,以方便下次读取 37 38 q= queue.Queue() 39 WEvent = Event() 40 REvent = Event() 41 t1= WriteThread( q, WEvent, REvent) 42 t2 = ReadThread(q, WEvent, REvent) 43 44 t1.start()
45 t2.start()