领会下面这个示例吧,其实跟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()

上面的源码可知,__enter__方法就是accquire一把锁. __ exit__方法 最终是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

线程协作之threading.Condition的更多相关文章

  1. 线程锁、threading.local(flask源码中用的到)、线程池、生产者消费者模型

    一.线程锁 线程安全,多线程操作时,内部会让所有线程排队处理.如:list/dict/Queue 线程不安全 + 人(锁) => 排队处理 1.RLock/Lock:一次放一个 a.创建10个线 ...

  2. CUDA线程协作之共享存储器“__shared__”&&“__syncthreads()”

    在GPU并行编程中,一般情况下,各个处理器都需要了解其他处理器的执行状态,在各个并行副本之间进行通信和协作,这涉及到不同线程间的通信机制和并行执行线程的同步机制. 共享内存"__share_ ...

  3. python线程的条件变量Condition的用法实例

      Condition 对象就是条件变量,它总是与某种锁相关联,可以是外部传入的锁或是系统默认创建的锁.当几个条件变量共享一个锁时,你就应该自己传入一个锁.这个锁不需要你操心,Condition 类会 ...

  4. python的threading的使用(join方法,多线程,锁threading.Lock和threading.Condition

    一.开启多线程方法一 import threading,time def write1(): for i in range(1,5): print('1') time.sleep(1) def wri ...

  5. 基于 Java 2 运行时安全模型的线程协作--转

    在 Java 2 之前的版本,运行时的安全模型使用非常严格受限的沙箱模型(Sandbox).读者应该熟悉,Java 不受信的 Applet 代码就是基于这个严格受限的沙箱模型来提供运行时的安全检查.沙 ...

  6. 【Java线程】Lock、Condition

    http://www.infoq.com/cn/articles/java-memory-model-5  深入理解Java内存模型(五)——锁 http://www.ibm.com/develope ...

  7. java线程系列之三(线程协作)

    本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7433673,转载请注明. 上一篇讲述了线程的互斥(同步),但是在很多情况 ...

  8. Python线程的用法 函数式线程_thread和threading 样例

    函数式线程写起来比较简单,但是功能没有threading那么高级,先来个函数式编程样例: #!/usr/bin/python #coding: utf-8 #————————————————————— ...

  9. python 线程间通信之Condition, Queue

    Event 和 Condition 是threading模块原生提供的模块,原理简单,功能单一,它能发送 True 和 False 的指令,所以只能适用于某些简单的场景中. 而Queue则是比较高级的 ...

随机推荐

  1. flutter dialog异常Another exception was thrown: Navigator operation requested with a context that does not include a Navigator

    我在使用flutter里的对话框控件的时候遇到了一个奇怪的错误 Another exception was thrown: Navigator operation requested with a c ...

  2. linux系统查找大文件脚本

    每次遇到服务器磁盘满,都会很苦恼,但有了下面两种方法就可以轻松找到机器中的大文件了, 第一种:du -sh du -sh 当前目录下个文件或目录的大小: du -sh * 显示前10个占用空间最大的文 ...

  3. 简单的遍历xml

    #include <opencv2\opencv.hpp> #include <opencv2\highgui\highgui.hpp> #include <opencv ...

  4. JS 数组的常用方法详解归纳之改变原数组方法

    shift() 把数组的第一个元素从其中删除,并返回第一个元素的值, 如果数组是空的,那么 shift() 方法将不进行任何操作,返回 undefined 值.请注意,该方法不创建新数组,而是直接修改 ...

  5. 【Linux-驱动】驱动策略----自旋锁

    自旋锁 自旋锁最多只能被一个内核任务持有.要是锁未被持有,请求它的内核任务便会立即得到它并继续执行.如果一个内核任务试图请求一个已经被别的内核任务持有的自旋锁,那么CPU就会一直尽心循环---旋转-- ...

  6. 02:django model数据库操作

    Django其他篇 目录: 1.1 Django中使用MySQL 1.2 创建表 1.3 Django一对多表结构操作 1.4 Django多对多表结构操作 1.5 一大波Model操作 1.6 Mo ...

  7. 17: VUE数据绑定 与 Object.defineProperty

    VUE数据绑定原理:https://segmentfault.com/a/1190000006599500?utm_source=tag-newest Object.defineProperty(): ...

  8. 1、Java语言概述与开发环境——JDK的安装与环境变量的配置

    Selenium.Appium.Macaca.RobotFramework.Jmeter等框架或工具均必须的一样东西——JDK,也就是基于java开发的东西都要这个东西.JDK的概念在这里不作描述. ...

  9. Python 入门之Python简介

    Python 入门之Python简介 1.Python简介: (1) Python的出生: ​ python的创始人为吉多·范罗苏姆(Guido van Rossum)(中文名字:龟叔).1989年的 ...

  10. 动态规划(股票交易)---只能进行 k 次的股票交易

    只能进行 k 次的股票交易 188. Best Time to Buy and Sell Stock IV (Hard) 题目描述:   只能进行K次股票交易,求能获得的最大利润 思路分析:   和只 ...