侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python的条件锁与事件共享详解

Python  /  管理员 发布于 7年前   175

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();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();# 等待写事件 带来      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:唤起所有线程,防止线程永远处于沉默状态 。

模版:

基本codefrom threading import Threadfrom threading import Conditionimport randomimport timelock=Condition(); # 声明条件锁flag=0;def cnsumer():  lock.acquire();  while flag==0:    lock.wait();    业务代码---    lock.relarse();   def product():  lock.acquire();    释放锁之前对控制变量进行操作,数据的操作控制 可以作为全局变量来锁定  lock.notifyALl();  lock.relarse();

参考代码code:

# -*- coding: utf-8 -*-"""Created on Wed Sep 11 21:40:41 2019@author: DGW-PC"""# 条件锁生产者消费者from threading import Threadfrom threading import Conditionimport randomimport timeflag=0; # 声明控制标志goods=0; # 事物表示lock=Condition();def consumer(x):  global flag;  global goods;  lock.acquire(); # 取得锁  while flag==0: # 便于多次进行消费     print("consumer %d进入等待" % x);     lock.wait();  print("consumer {0}:消费了{1}".format(x,goods));# format 次序从0开始  flag-=1;  lock.release(); #释放锁  def product(x):  global flag;  global goods;  time.sleep(3);  lock.acquire();  goods=random.randint(1,1000);  print("product {0} 产生了{1}".format(x,goods));  flag+=1;  lock.notifyAll();  lock.release();threads=[];for i in range(0,2):  t1=Thread(target=consumer,args=(i,));  t2=Thread(target=product,args=(i,));  t1.start();  t2.start();  threads.append(t1);  threads.append(t2);for x in threads:  x.join();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python socket非阻塞模块应用示例
    下一条:
    Python的互斥锁与信号量详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客