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使用rsa加密算法模块模拟新浪微博登录
Jan 22 Python
Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
May 06 Python
Python利用前序和中序遍历结果重建二叉树的方法
Apr 27 Python
Python将多个excel文件合并为一个文件
Jan 03 Python
PyQT实现多窗口切换
Apr 20 Python
python 实现在txt指定行追加文本的方法
Apr 29 Python
Python实现正则表达式匹配任意的邮箱方法
Dec 20 Python
pandas去除重复列的实现方法
Jan 29 Python
python实现接口并发测试脚本
Jun 25 Python
浅谈django2.0 ForeignKey参数的变化
Aug 06 Python
python实现发送form-data数据的方法详解
Sep 27 Python
python实现简单的井字棋
May 26 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
apache rewrite_module模块使用教程
2008/01/10 PHP
Ajax+PHP 边学边练之四 表单
2009/11/27 PHP
初学Javascript的一些总结
2008/11/03 Javascript
通过隐藏option实现select的联动效果
2009/11/10 Javascript
解析使用js判断只能输入数字、字母等验证的方法(总结)
2013/05/14 Javascript
用js+iframe形成页面的一种遮罩效果的具体实现
2013/12/31 Javascript
浅析js中的浮点型运算问题
2014/01/06 Javascript
Bootstrap精简教程
2015/11/27 Javascript
浅析JS原型继承与类的继承
2016/04/07 Javascript
javascript经典特效分享 手风琴、轮播图、图片滑动
2016/09/14 Javascript
深入理解Vue2.x的虚拟DOM diff原理
2017/09/27 Javascript
ES6中javascript实现函数绑定及类的事件绑定功能详解
2017/11/08 Javascript
Ionic学习日记实现验证码倒计时
2018/02/08 Javascript
javaScript动态添加Li元素的实例
2018/02/24 Javascript
nodejs acl的用户权限管理详解
2018/03/14 NodeJs
在Node.js下运用MQTT协议实现即时通讯及离线推送的方法
2019/01/24 Javascript
移动端(微信等使用vConsole调试console的方法
2019/03/05 Javascript
python实现socket端口重定向示例
2014/02/10 Python
举例讲解Python的lambda语句声明匿名函数的用法
2016/07/01 Python
python 根据时间来生成唯一的字符串方法
2019/01/14 Python
Python中将两个或多个list合成一个list的方法小结
2019/05/12 Python
Python实现加密的RAR文件解压的方法(密码已知)
2020/09/11 Python
python实现粒子群算法
2020/10/15 Python
Numpy中np.max的用法及np.maximum区别
2020/11/27 Python
matplotlib事件处理基础(事件绑定、事件属性)
2021/02/03 Python
python实现学生信息管理系统源码
2021/02/22 Python
公司前台辞职报告
2014/01/19 职场文书
运动会广播稿20字
2014/02/18 职场文书
物理系毕业生自荐书范文
2014/02/22 职场文书
2014年大学庆元旦迎新年活动方案
2014/03/09 职场文书
酒店优秀员工事迹材料
2014/06/02 职场文书
毕业证委托书范文
2014/09/26 职场文书
2016中秋节问候语
2015/11/11 职场文书
python 利用PyAutoGUI快速构建自动化操作脚本
2021/05/31 Python
一文彻底理解js原生语法prototype,__proto__和constructor
2021/10/24 Javascript
Mysql 文件配置解析介绍
2022/05/06 MySQL