领会下面这个示例吧,其实跟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__时的那把锁"htmlcode">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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python线程协作threading.Condition实现过程解析”评论...
更新日志
2024年11月08日
2024年11月08日
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]