当前位置: 移动技术网 > IT编程>脚本编程>Python > Python线程条件变量Condition原理解析

Python线程条件变量Condition原理解析

2020年03月09日  | 移动技术网IT编程  | 我要评论

希特勒nobody,武藤兰道图片21p护士,辉跃经典

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网