线程协作之threading.Condition
领会下面这个示例吧,其实跟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的更多相关文章
- 线程锁、threading.local(flask源码中用的到)、线程池、生产者消费者模型
一.线程锁 线程安全,多线程操作时,内部会让所有线程排队处理.如:list/dict/Queue 线程不安全 + 人(锁) => 排队处理 1.RLock/Lock:一次放一个 a.创建10个线 ...
- CUDA线程协作之共享存储器“__shared__”&&“__syncthreads()”
在GPU并行编程中,一般情况下,各个处理器都需要了解其他处理器的执行状态,在各个并行副本之间进行通信和协作,这涉及到不同线程间的通信机制和并行执行线程的同步机制. 共享内存"__share_ ...
- python线程的条件变量Condition的用法实例
Condition 对象就是条件变量,它总是与某种锁相关联,可以是外部传入的锁或是系统默认创建的锁.当几个条件变量共享一个锁时,你就应该自己传入一个锁.这个锁不需要你操心,Condition 类会 ...
- 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 ...
- 基于 Java 2 运行时安全模型的线程协作--转
在 Java 2 之前的版本,运行时的安全模型使用非常严格受限的沙箱模型(Sandbox).读者应该熟悉,Java 不受信的 Applet 代码就是基于这个严格受限的沙箱模型来提供运行时的安全检查.沙 ...
- 【Java线程】Lock、Condition
http://www.infoq.com/cn/articles/java-memory-model-5 深入理解Java内存模型(五)——锁 http://www.ibm.com/develope ...
- java线程系列之三(线程协作)
本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7433673,转载请注明. 上一篇讲述了线程的互斥(同步),但是在很多情况 ...
- Python线程的用法 函数式线程_thread和threading 样例
函数式线程写起来比较简单,但是功能没有threading那么高级,先来个函数式编程样例: #!/usr/bin/python #coding: utf-8 #————————————————————— ...
- python 线程间通信之Condition, Queue
Event 和 Condition 是threading模块原生提供的模块,原理简单,功能单一,它能发送 True 和 False 的指令,所以只能适用于某些简单的场景中. 而Queue则是比较高级的 ...
随机推荐
- 用JS实现移动的窗口
https://blog.csdn.net/iteye_21064/article/details/81496640 用JS实现移动的窗口 2007年09月06日 23:23:00 阅读数:3 很简单 ...
- 获取win10壁纸
执行命令会将所有壁纸拷贝到桌面上的wallpaper文件夹内 bat xcopy %LOCALAPPDATA%\Packages\Microsoft.Windows.ContentDeliveryMa ...
- LeetCode算法题-Magic Squares In Grid(Java实现)
这是悦乐书的第326次更新,第349篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第196题(顺位题号是840).3 x 3魔方是一个3 x 3网格,填充了从1到9的不同 ...
- 数据结构系列之2-3树的插入、查找、删除和遍历完整版代码实现(dart语言实现)
弄懂了二叉树以后,再来看2-3树.网上.书上看了一堆文章和讲解,大部分是概念,很少有代码实现,尤其是删除操作的代码实现.当然,因为2-3树的特性,插入和删除都是比较复杂的,因此经过思考,独创了删除时分 ...
- maven项目的导包问题,已经加载jar包了可是idea检测不到
1.详细请参考 https://blog.csdn.net/brainhang/article/details/76725080 把测试模式注释即可
- 精读《Optional chaining》
1. 引言 备受开发者喜爱的特性 Optional chaining 在 2019.6.5 进入了 stage2,让我们详细读一下草案,了解一下这个特性的用法以及讨论要点. 借着这次精读草案,让我们了 ...
- SQL Server中的扩展事件学习系列
SQL Server 扩展事件(Extented Events)从入门到进阶(1)——从SQL Trace到Extented Events SQL Server 扩展事件(Extented Event ...
- SSIS包定时执行
企业管理器 --管理 --SQL Server代理 --右键作业 --新建作业 --"常规"项中输入作业名称 --"步骤"项 --新建 --"步骤名& ...
- Linux 最常用命令整理,建议收藏!
Linux是目前应用最广泛的服务器操作系统,基于Unix,开源免费,由于系统的稳定性和安全性,市场占有率很高,几乎成为程序代码运行的最佳系统环境. linux不仅可以长时间的运行我们编写的程序代码,还 ...
- c++多线程并发学习笔记(1)
共享数据带来的问题:条件竞争 避免恶性条件竞争的方法: 1. 对数据结构采用某种保护机制,确保只有进行修改的线程才能看到修改时的中间状态.从其他访问线程的角度来看,修改不是已经完成了,就是还没开始. ...