温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python线程条件变量Condition解析

发布时间:2020-08-12 13:49:06 来源:ITPUB博客 阅读:152 作者:安全剑客 栏目:编程语言
这篇文章主要介绍了Python线程条件变量Condition原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了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.linuxprobe.com/python-condition-parsing.html

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI