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 相关文章推荐
python解析json实例方法
Nov 19 Python
Python实现把xml或xsl转换为html格式
Apr 08 Python
Python实现PS滤镜的旋转模糊功能示例
Jan 20 Python
Python实现的基于优先等级分配糖果问题算法示例
Apr 25 Python
python通过Windows下远程控制Linux系统
Jun 20 Python
如何在django里上传csv文件并进行入库处理的方法
Jan 02 Python
python 使用pandas计算累积求和的方法
Feb 08 Python
解决Pycharm调用Turtle时 窗口一闪而过的问题
Feb 16 Python
利用python list完成最简单的DB连接池方法
Aug 09 Python
Python实现微信机器人的方法
Sep 06 Python
python计算无向图节点度的实例代码
Nov 22 Python
pytorch模型存储的2种实现方法
Feb 14 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
6种php上传图片重命名的方法实例
2013/11/04 PHP
浅谈PHP命令执行php文件需要注意的问题
2016/12/16 PHP
自制PHP框架之模型与数据库
2017/05/07 PHP
[IE&FireFox兼容]JS对select操作
2007/01/07 Javascript
jQuery编辑器KindEditor4.1.4代码高亮显示设置教程
2013/03/01 Javascript
JavaScript获取客户端计算机硬件及系统等信息的方法
2014/01/02 Javascript
JS调用页面表格导出excel示例代码
2014/03/18 Javascript
jquery 为a标签绑定click事件示例代码
2014/06/23 Javascript
Node.js的特点和应用场景介绍
2014/11/04 Javascript
jQuery中slice()方法用法实例
2015/01/07 Javascript
jquery性能优化高级技巧
2015/08/24 Javascript
【经验总结】编写JavaScript代码时应遵循的14条规律
2016/06/20 Javascript
用nodejs的实现原理和搭建服务器(动态)
2016/08/10 NodeJs
深入解析ES6中的promise
2018/11/08 Javascript
JS中比较两个Object数组是否相等方法实例
2019/11/11 Javascript
js实现上传按钮并显示缩略图小轮子
2020/05/04 Javascript
微信小程序以7天为周期连续签到7天功能效果的示例代码
2020/08/20 Javascript
Python实现合并excel表格的方法分析
2019/04/13 Python
利用python将图片版PDF转文字版PDF
2019/05/03 Python
python处理excel绘制雷达图
2019/10/18 Python
python根据文本生成词云图代码实例
2019/11/15 Python
PyTorch的自适应池化Adaptive Pooling实例
2020/01/03 Python
Python txt文件常用读写操作代码实例
2020/08/03 Python
Python fileinput模块如何逐行读取多个文件
2020/10/05 Python
如何利用pycharm进行代码更新比较
2020/11/04 Python
CSS3教程(10):CSS3 HSL声明设置颜色
2009/04/02 HTML / CSS
英国航空官网:British Airways
2016/09/11 全球购物
Melissa鞋英国官方网站:Nonnon
2019/05/01 全球购物
交通事故赔偿协议书
2014/04/15 职场文书
小学生操行评语
2014/04/22 职场文书
村党支部群众路线教育实践活动对照检查材料
2014/09/26 职场文书
老兵退伍感言
2015/08/03 职场文书
小学语文教学随笔
2015/08/14 职场文书
护士旷工检讨书
2015/08/15 职场文书
资产移交协议书
2016/03/24 职场文书
简述Java中throw-throws异常抛出
2021/08/07 Java/Android