领会下面这个示例吧,其实跟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. Android - Unable to add window android.view.ViewRootImpl$W@6518342 -- permission denied for window type 2133

    因为跟博主碰到了一样的问题,所以记录一下分析原理 原文链接:https://www.jianshu.com/p/b0364074288a 首先,先介绍下背景环境,第一,是Android7.0,其次,要 ...

  2. Canvas入门05-渐变颜色

    线性渐变API: ctx.createLinearGradient(double x1, double y1, double x2, double y2) 创建一个渐变实例 (x1, y1) 渐变的起 ...

  3. ubuntu 虚拟机安装

    ubuntu16.04.5 LTS 安装   1.下载ubuntu镜像 打开ubuntu官网镜像地址https://launchpad.net/ubuntu/+cdmirrors 在上面中搜索chin ...

  4. [Git] 017 加一条分支,享双倍快乐

    0. 回顾 [Git] 009 逆转未来 中的 "2.2" 讲过 git checkout -- <file> 这回的 git checkout <branch_ ...

  5. 浅拷贝&深拷贝

    浅拷贝新的对象指向原来对象的地址 深拷贝新的对象中,原来是可变对象,会新复制一份值指向新的地址[11,22,33]若原来的对象里含有可变对象,里面的这个可变对象也会指向新的地址['qwer', 123 ...

  6. MySql-Mysql技术内幕~SQL编程学习笔记(N)

    1._rowid 类似Oracle的rowid mysql> ; +-------+----+----------------+-------------+---------------+--- ...

  7. CentOS 7安装Python 2.6(与已有版本共存)

    1. 安装需要用到的包 yum install -y zlib-devel bzip2-devel openssl-devel xz-libs wget 2. 下载 Python 2.6.8 版本 w ...

  8. Spark启动流程(Standalone)-分析

    1.start-all.sh脚本,实际上执行java -cp Master 和 java -cp Worker 2.Master 启动时首先穿件一个RpcEnv对象,负责管理所有通信逻辑 3.Mast ...

  9. [BZOJ 3625] [Codeforces 438E] 小朋友的二叉树 (DP+生成函数+多项式开根+多项式求逆)

    [BZOJ 3625] [Codeforces 438E] 小朋友的二叉树 (DP+生成函数+多项式开根+多项式求逆) 题面 一棵二叉树的所有点的点权都是给定的集合中的一个数. 让你求出1到m中所有权 ...

  10. 【NOI2007】项链工厂 ——老题新做.jpg

    第一次是用 ODT 过的...(虽说跑得飞慢但它就是能过) 而且还写了发题解... 第二次是在考场上碰到了这道题,然后居然打了线段树,各种 bug 直接让代码爆零 但还是补好了代码重新交了一发,发现跑 ...