神剑山庄资源网 Design By www.hcban.com

这篇文章主要介绍了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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
Python,线程,条件变量,Condition

神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com

评论“Python线程条件变量Condition原理解析”

暂无Python线程条件变量Condition原理解析的评论...

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。