Python事件机制
事件机制:
这是线程间最简单的通信机制:一个线程发送事件,其他线程等待事件
事件机制使用一个内部的标志,使用set方法进行使能为True,使用clear清除为false
wait方法将会阻塞当前线程知道标记为True
import queue from random import randint from threading import Thread from threading import Event class WriteThread(Thread): def __init__(self,queue,WEvent,REvent): Thread.__init__(self) self.queue = queue self.REvent = REvent self.WEvent = WEvent def run(self): data = [randint(1,10) for _ in range(0,5)] self.queue.put(data) print("send Read Event") self.REvent.set() #--> 通知读线程可以读了 self.WEvent.wait() #--> 等待写事件 print("recv write Event") self.WEvent.clear() #-->清除写事件,以方便下次读取 class ReadThread(Thread): def __init__(self,queue,WEvent, REvent): Thread.__init__(self) self.queue = queue self.REvent = REvent self.WEvent = WEvent def run(self): while True: self.REvent.wait() #--> 等待读事件 print("recv Read Event") data = self.queue.get() print("read data is {0}".format(data)) print("Send Write Event") self.WEvent.set() #--> 发送写事件 self.REvent.clear() #--> 清除读事件,以方便下次读取 q= queue.Queue() WEvent = Event() REvent = Event() WThread = WriteThread( q, WEvent, REvent) RThread = ReadThread(q, WEvent, REvent) WThread.start() RThread.start()
结果:
send Read Event recv Read Event read data is [9, 4, 8, 3, 5] Send Write Event recv write Event
时间: 2024-11-07 07:18:29