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中吸引人的一些特性
Apr 09 Python
Python探索之静态方法和类方法的区别详解
Oct 27 Python
[原创]pip和pygal的安装实例教程
Dec 07 Python
Python读取Pickle文件信息并计算与当前时间间隔的方法分析
Jan 30 Python
使用Python实现将list中的每一项的首字母大写
Jun 11 Python
Django  ORM 练习题及答案
Jul 19 Python
Django用户认证系统 User对象解析
Aug 02 Python
python numpy 常用随机数的产生方法的实现
Aug 21 Python
使用Python串口实时显示数据并绘图的例子
Dec 26 Python
django 数据库返回queryset实现封装为字典
May 19 Python
Python学习之路安装pycharm的教程详解
Jun 17 Python
Python爬虫之Selenium实现窗口截图
Dec 04 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
浅析十款PHP开发框架的对比
2013/07/05 PHP
CodeIgniter框架数据库事务处理的设计缺陷和解决方案
2014/07/25 PHP
thinkphp使用literal防止模板标签被解析的方法
2014/11/22 PHP
CI框架AR数据库操作常用函数总结
2016/11/21 PHP
laravel5.6 框架邮件队列database驱动简单demo示例
2020/01/26 PHP
用 Javascript 验证表单(form)中多选框(checkbox)值
2009/09/08 Javascript
详细介绍8款超实用JavaScript框架
2013/10/25 Javascript
jquery解析JSON数据示例代码
2014/03/17 Javascript
NodeJS学习笔记之网络编程
2014/08/03 NodeJs
JavaScript组件焦点与页内锚点间传值的方法
2015/02/02 Javascript
在ASP.NET MVC项目中使用RequireJS库的用法示例
2016/02/15 Javascript
手机浏览器 后退按钮强制刷新页面方法总结
2016/10/09 Javascript
Vue 过滤器filters及基本用法
2017/12/26 Javascript
layer.close()关闭进度条和Iframe窗的方法
2018/08/17 Javascript
iview实现select tree树形下拉框的示例代码
2018/12/21 Javascript
使用vue实现多规格选择实例(SKU)
2019/08/23 Javascript
jquery.validate自定义验证用法实例分析【成功提示与择要提示】
2020/06/06 jQuery
JS实现页面鼠标点击出现图片特效
2020/08/19 Javascript
python中使用sys模板和logging模块获取行号和函数名的方法
2014/04/15 Python
深入解析Python编程中JSON模块的使用
2015/10/15 Python
Python实现FTP上传文件或文件夹实例(递归)
2017/01/16 Python
Python绘制七段数码管实例代码
2017/12/20 Python
python递归实现快速排序
2018/08/18 Python
分享8个非常流行的 Python 可视化工具包
2019/06/05 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
2019/11/16 Python
Python字典底层实现原理详解
2019/12/18 Python
pytorch 归一化与反归一化实例
2019/12/31 Python
python json load json 数据后出现乱序的解决方案
2020/02/27 Python
Python logging模块写入中文出现乱码
2020/05/21 Python
html5实现的便签特效(实战分享)
2013/11/29 HTML / CSS
波兰珠宝品牌:YES
2019/08/09 全球购物
Puma印度官网:德国运动品牌
2019/10/06 全球购物
JMS中Topic和Queue有什么区别
2013/05/15 面试题
网络编辑求职信
2014/04/30 职场文书
2015年共青团工作总结
2015/05/15 职场文书
公司岗位说明书
2015/10/08 职场文书