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 相关文章推荐
flask中使用SQLAlchemy进行辅助开发的代码
Feb 10 Python
Python内置函数的用法实例教程
Sep 08 Python
Python中的列表知识点汇总
Apr 14 Python
python操作oracle的完整教程分享
Jan 30 Python
python抓取网站的图片并下载到本地的方法
May 22 Python
基于python实现简单日历
Jul 28 Python
python求质数的3种方法
Sep 28 Python
django foreignkey外键使用的例子 相当于left join
Aug 06 Python
浅析python标准库中的glob
Mar 13 Python
python和js交互调用的方法
Jun 23 Python
推荐技术人员一款Python开源库(造数据神器)
Jul 08 Python
Python进程间的通信之语法学习
Apr 11 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/06/26 PHP
分享一则PHP定义函数代码
2015/02/26 PHP
如何在HTML 中嵌入 PHP 代码
2015/05/13 PHP
jQuery学习笔记 操作jQuery对象 文档处理
2012/09/19 Javascript
JQuery对class属性的操作实现按钮开关效果
2013/10/11 Javascript
JavaScript中String.prototype用法实例
2015/05/20 Javascript
node.js实现博客小爬虫的实例代码
2016/10/08 Javascript
vue.js的computed,filter,get,set的用法及区别详解
2018/03/08 Javascript
vue中的数据绑定原理的实现
2018/07/02 Javascript
解决vue接口数据赋值给data没有反应的问题
2018/08/27 Javascript
ES6 class的应用实例分析
2019/06/27 Javascript
Vue中关闭弹窗组件时销毁并隐藏操作
2020/09/01 Javascript
微信小程序实现倒计时功能
2020/11/19 Javascript
vue中如何自定义右键菜单详解
2020/12/08 Vue.js
[01:42]辉夜杯战队访谈宣传片—FANTUAN
2015/12/25 DOTA
Python使用urllib模块的urlopen超时问题解决方法
2014/11/08 Python
Python中实现参数类型检查的简单方法
2015/04/21 Python
python数组复制拷贝的实现方法
2015/06/09 Python
Django ORM框架的定时任务如何使用详解
2017/10/19 Python
Python函数生成器原理及使用详解
2020/03/12 Python
Django choices下拉列表绑定实例
2020/03/13 Python
python适合做数据挖掘吗
2020/06/16 Python
TensorFlow保存TensorBoard图像操作
2020/06/23 Python
Python获取指定网段正在使用的IP
2020/12/14 Python
基于CSS3实现的黑色个性导航菜单效果
2015/09/14 HTML / CSS
比利时香水网上商店:NOTINO
2018/03/28 全球购物
Ray-Ban雷朋西班牙官网:全球领先的太阳眼镜品牌
2018/11/28 全球购物
UNIX文件系统常用命令
2012/05/25 面试题
物理研修随笔感言
2014/02/14 职场文书
《最后的姿势》教学反思
2014/02/27 职场文书
《三亚落日》教学反思
2014/04/26 职场文书
社区矫正工作方案
2014/06/04 职场文书
感恩老师演讲稿600字
2014/08/28 职场文书
2016年教师师德师风心得体会
2016/01/12 职场文书
2019年农民幸福观调查的实践感悟
2019/12/19 职场文书
Spring Boot 使用 Spring-Retry 进行重试框架
2022/04/24 Java/Android