Python线程协作threading.Condition实现过程解析


Posted in Python onMarch 12, 2020

领会下面这个示例吧,其实跟java中wait/nofity是一样一样的道理

import threading


# 条件变量,用于复杂的线程间同步锁
"""
需求:
  男:小姐姐,你好呀!
  女:哼,想泡老娘不成?
  男:对呀,想泡你
  女:滚蛋,门都没有!
  男:切,长这么丑, 还这么吊...
  女:关你鸟事!

"""
class Boy(threading.Thread):
  def __init__(self, name, condition):
    super().__init__(name=name)
    self.condition = condition

  def run(self):
    with self.condition:
      print("{}:小姐姐,你好呀!".format(self.name))
      self.condition.wait()
      self.condition.notify()

      print("{}:对呀,想泡你".format(self.name))
      self.condition.wait()
      self.condition.notify()

      print("{}:切,长这么丑, 还这么吊...".format(self.name))
      self.condition.wait()
      self.condition.notify()


class Girl(threading.Thread):
  def __init__(self, name, condition):
    super().__init__(name=name)
    self.condition = condition

  def run(self):
    with self.condition:
      print("{}:哼,想泡老娘不成?".format(self.name))
      self.condition.notify()
      self.condition.wait()

      print("{}:滚蛋,门都没有!".format(self.name))
      self.condition.notify()
      self.condition.wait()

      print("{}:关你鸟事!".format(self.name))
      self.condition.notify()
      self.condition.wait()


if __name__ == '__main__':
  condition = threading.Condition()
  boy_thread = Boy('男', condition)
  girl_thread = Girl('女', condition)

  boy_thread.start()
  girl_thread.start()

Condition的底层实现了__enter__和 __exit__协议.所以可以使用with上下文管理器

由Condition的__init__方法可知,它的底层也是维护了一个RLock锁

def __enter__(self):
    return self._lock.__enter__()
def __exit__(self, *args):
    return self._lock.__exit__(*args)
def __exit__(self, t, v, tb):
    self.release()
def release(self):
    """Release a lock, decrementing the recursion level.

    If after the decrement it is zero, reset the lock to unlocked (not owned
    by any thread), and if any other threads are blocked waiting for the
    lock to become unlocked, allow exactly one of them to proceed. If after
    the decrement the recursion level is still nonzero, the lock remains
    locked and owned by the calling thread.

    Only call this method when the calling thread owns the lock. A
    RuntimeError is raised if this method is called when the lock is
    unlocked.

    There is no return value.

    """
    if self._owner != get_ident():
      raise RuntimeError("cannot release un-acquired lock")
    self._count = count = self._count - 1
    if not count:
      self._owner = None
      self._block.release()

至于wait/notify是如何操作的,还是有点懵.....

wait()方法源码中这样三行代码

waiter = _allocate_lock() #从底层获取了一把锁,并非Lock锁
waiter.acquire()
self._waiters.append(waiter) # 然后将这个锁加入到_waiters(deque)中
saved_state = self._release_save() # 这是释放__enter__时的那把锁???

notify()方法源码

all_waiters = self._waiters  
waiters_to_notify = _deque(_islice(all_waiters, n))# 从_waiters中取出n个
if not waiters_to_notify:  # 如果是None,结束
   return
for waiter in waiters_to_notify: # 循环release
   waiter.release()
   try:
     all_waiters.remove(waiter) #从_waiters中移除
   except ValueError:
     pass

大体意思: wait先从底层创建锁,acquire, 放到一个deque中,然后释放掉with锁, notify时,从deque取拿出锁,release

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

Python 相关文章推荐
django通过ajax发起请求返回JSON格式数据的方法
Jun 04 Python
Python实现批量修改文件名实例
Jul 08 Python
Python将多个excel文件合并为一个文件
Jan 03 Python
python with提前退出遇到的坑与解决方案
Jan 05 Python
对python使用telnet实现弱密码登录的方法详解
Jan 26 Python
python实现手机销售管理系统
Mar 19 Python
详解Django项目中模板标签及模板的继承与引用(网站中快速布置广告)
Mar 27 Python
Python绘制股票移动均线的实例
Aug 24 Python
tensorboard实现同时显示训练曲线和测试曲线
Jan 21 Python
Python生成器传参数及返回值原理解析
Jul 22 Python
python selenium 获取接口数据的实现
Dec 07 Python
Python实现批量将文件复制到新的目录中再修改名称
Apr 12 Python
Python 实现网课实时监控自动签到、打卡功能
Mar 12 #Python
Python基于read(size)方法读取超大文件
Mar 12 #Python
Python函数生成器原理及使用详解
Mar 12 #Python
python deque模块简单使用代码实例
Mar 12 #Python
python中安装django模块的方法
Mar 12 #Python
python3 sorted 如何实现自定义排序标准
Mar 12 #Python
Python dict和defaultdict使用实例解析
Mar 12 #Python
You might like
如何批量替换相对地址为绝对地址(利用bat批处理实现)
2013/05/27 PHP
解析用PHP实现var_export的详细介绍
2013/06/20 PHP
php实现网站顶踩功能的完整前端代码
2015/07/19 PHP
基于ThinkPHP实现批量删除
2015/12/18 PHP
thinkphp诸多限制条件下如何getshell详解
2020/12/09 PHP
javascript 特殊字符串
2009/02/25 Javascript
向当前style sheet中插入一个新的style实现方法
2013/04/01 Javascript
Jquery获取复选框被选中值的简单方法
2013/07/04 Javascript
Seajs的学习笔记
2014/03/04 Javascript
php析构函数的具体用法小结
2014/03/11 Javascript
javascript继承机制实例详解
2014/11/20 Javascript
jQuery实现简单二级下拉菜单
2015/04/12 Javascript
JS实现兼容各种浏览器的获取选择文本的方法【测试可用】
2016/06/21 Javascript
JS上传图片预览插件制作(兼容到IE6)
2016/08/07 Javascript
谈谈vue中mixin的一点理解
2017/12/12 Javascript
VeeValidate在vue项目里表单校验应用案例
2018/05/09 Javascript
AngularJS修改model值时,显示内容不变的实例
2018/09/13 Javascript
JS实现的图片选择顺序切换和循环切换功能示例【测试可用】
2018/12/28 Javascript
this.$toast() 了解一下?
2019/04/18 Javascript
vue-froala-wysiwyg 富文本编辑器功能
2019/09/19 Javascript
js实现盒子移动动画效果
2020/08/09 Javascript
vant中的toast轻提示实现代码
2020/11/04 Javascript
Python列表计数及插入实例
2014/12/17 Python
Python网页解析利器BeautifulSoup安装使用介绍
2015/03/17 Python
Python自动化运维和部署项目工具Fabric使用实例
2016/09/18 Python
浅谈python 读excel数值为浮点型的问题
2018/12/25 Python
Django web自定义通用权限控制实现方法
2020/11/24 Python
利用CSS3的transform做的动态时钟效果
2011/09/21 HTML / CSS
BASIC HOUSE官方旗舰店:韩国著名的服装品牌
2018/09/27 全球购物
Hello Molly美国:女性时尚在线
2019/08/26 全球购物
Edwaybuy西班牙:小米在线商店
2019/12/04 全球购物
Web Service面试题:如何搭建Axis2的开发环境
2012/06/20 面试题
物流创业计划书
2014/02/01 职场文书
中学生个人自我评价
2014/02/06 职场文书
迎新晚会主持词
2014/03/24 职场文书
运动会3000米加油稿
2015/07/21 职场文书