Python线程条件变量Condition原理解析
作者:虚生 时间:2022-07-23 02:52:06
这篇文章主要介绍了Python线程条件变量Condition原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Condition 对象就是条件变量,它总是与某种锁相关联,可以是外部传入的锁或是系统默认创建的锁。当几个条件变量共享一个锁时,你就应该自己传入一个锁。这个锁不需要你操心,Condition 类会管理它。
acquire() 和 release() 可以操控这个相关联的锁。其他的方法都必须在这个锁被锁上的情况下使用。wait() 会释放这个锁,阻塞本线程直到其他线程通过 notify() 或 notify_all() 来唤醒它。一旦被唤醒,这个锁又被 wait() 锁上。
经典的 consumer/producer 问题的代码示例为:
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
def consumer(cv):
logging.debug('Consumer thread started ...')
with cv:
logging.debug('Consumer waiting ...')
cv.acquire()
cv.wait()
logging.debug('Consumer consumed the resource')
cv.release()
def producer(cv):
logging.debug('Producer thread started ...')
with cv:
cv.acquire()
logging.debug('Making resource available')
logging.debug('Notifying to all consumers')
cv.notify()
cv.release()
if __name__ == '__main__':
condition = threading.Condition()
cs1 = threading.Thread(name='consumer1', target=consumer, args=(condition,))
#cs2 = threading.Thread(name='consumer2', target=consumer, args=(condition,state))
pd = threading.Thread(name='producer', target=producer, args=(condition,))
cs1.start()
time.sleep(2)
#cs2.start()
#time.sleep(2)
pd.start()
来源:https://www.cnblogs.com/dylancao/p/12208923.html
标签:Python,线程,条件,变量,Condition


猜你喜欢
python对绑定事件的鼠标、按键的判断实例
2021-05-20 03:12:58
python根据完整路径获得盘名/路径名/文件名/文件扩展名的方法
2023-07-18 12:15:22
FFrpc python客户端lib使用解析
2023-09-06 00:12:20
PyQt5 PySide2 触摸测试功能的实现代码
2022-06-23 22:22:25

编写Smarty插件在模板中直接加载数据的详细介绍
2023-11-15 09:14:47
MySQL中UNION与UNION ALL的基本使用方法
2024-01-25 21:34:03

图文详解如何利用PyTorch实现图像识别
2023-02-04 00:54:13

python修改操作系统时间的方法
2022-10-14 14:13:29
基于Python爬取51cto博客页面信息过程解析
2023-06-11 16:27:37
python使用PIL模块获取图片像素点的方法
2022-07-28 10:57:57
Python代码调试的几种方法总结
2022-06-14 18:21:27

go实现文件的创建、删除与读取示例代码
2023-06-17 05:10:50
IE7异常CSS 导致内存破坏漏洞
2009-11-30 12:52:00
Python 实现PS滤镜中的径向模糊特效
2023-11-04 19:48:49

Python高级特性切片(Slice)操作详解
2022-04-07 20:28:02
python操作excel的方法(xlsxwriter包的使用)
2021-10-26 21:47:54
python中jieba模块的深入了解
2023-01-25 05:08:47

Python使用MYSQLDB实现从数据库中导出XML文件的方法
2024-01-14 21:03:01
楼层数横排比竖排好
2008-04-26 07:28:00

详解sql中的参照完整性(一对一,一对多,多对多)
2024-01-22 14:19:48
