Python的条件锁与事件共享

网友投稿 350 2022-08-23


Python的条件锁与事件共享

1:事件机制共享队列:

利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题要求:readthread读时,writethread不能写;writethread写时,readthread不能读。基本方法 时间类(Event)·set:设置事件。将标志位设为True。wait:等待事件。会将当前线程阻塞,直到标志位变为True。clear:清除事件。将标志位设为False。 set() clear() 函数的交替执行 也就是消息传递的本质

模版:

基本code# 事件消息机制import queueimport threadingimport randomfrom threading import Eventfrom threading import Threadclass 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,q,wt,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 queueimport threadingimport randomfrom threading import Eventfrom threading import Threadclass WriteThread(Thread): def __init__(self,q,wt,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(); 6class ReadThread(Thread): def __init__(self,q,wt,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,wt,rt); # 实例化对象的readthread=ReadThread(q,wt,rt); # 实例化对象的writethread.start();readthread.start();

2:条件锁同步生产者消费者

作用: 在保护互斥资源的基础上,增加了条件判断的机制 即为使用wait() 函数 判断不满足当前条件的基础上,让当前线程的阻塞。其他线程如果生成了满足了条件的资源 使用notify() notifyALl() 函数将刮起线程唤醒。使用了 threading 的Condition 类acquire() : 锁住当前资源relarse() :释放当前锁住的资源wait:挂起当前线程, 等待唤起 。• notify:唤起被 wait 函数挂起的线程 。• notif计All:唤起所有线程,防止线程永远处于沉默状态 。

模版:

参考代码code:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Pythoch 安装Apex(pytho程序师下载)
下一篇:Lombok如何快速构建JavaBean与日志输出
相关文章

 发表评论

暂时没有评论,来抢沙发吧~