Python的条件锁与事件共享
1:事件机制共享队列:利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题
基本code # 事件消息机制 import queue import threading import random from threading import Event from threading import Thread class WriteThread(Thread): def __init__(self,q,wt,rt): super().__init__(); self.queue=q; self.rt=rt; self.wt=wt; def run(self): self.rt.set() self.wt.wait(); self.wt.clear(); class ReadThread(Thread): def __init__(self,rt): super().__init__(); self.queue=q; self.rt=rt; self.wt=wt; def run(self): while True: self.rt.wait(); self.wt.wait(); self.wt.clear() ?
参考代码:
# -*- coding: utf-8 -*- """ Created on Tue Sep 10 20:10:10 2019 @author: DGW-PC """ # 事件消息机制 import queue import threading import random from threading import Event from threading import Thread class WriteThread(Thread): def __init__(self,rt): super().__init__(); self.queue=q; self.rt=rt; self.wt=wt; def run(self): data=[random.randint(1,100) for _ in range(0,10)]; self.queue.put(data); print("WriteThread写队列:",data); self.rt.set(); # 发送读事件 print("WriteThread通知读"); print("WriteThread等待写"); self.wt.wait(); print("WriteThread收到写事件"); self.wt.clear(); 6 class ReadThread(Thread): def __init__(self,rt): super().__init__(); self.queue=q; self.rt=rt; self.wt=wt; def run(self): while True: self.rt.wait();# 等待写事件 带来 print("ReadThread 收到读事件"); print("ReadThread 开始读{0}".format(self.queue.get())); print("ReadThread 发送写事件"); self.wt.set(); self.rt.clear(); q=queue.Queue(); rt=Event(); wt=Event(); writethread=WriteThread(q,rt); # 实例化对象的 readthread=ReadThread(q,rt); # 实例化对象的 writethread.start(); readthread.start(); ?
作用: 在保护互斥资源的基础上,增加了条件判断的机制 ?
|