zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    [SHOI2014]信号增幅仪
    [SDOI2016]征途
    Luogu P3226 [HNOI2012]集合选数
    Comet OJ C1076 [Contest #4]求和
    Luogu P2657 [SCOI2009]windy数
    Luogu P1864 [NOI2009]二叉查找树
    UVA10559 Blocks
    Luogu P1880 [NOI1995]石子合并
    简单DP
    CF1097F Alex and a TV Show
  • 原文地址:https://www.cnblogs.com/dylancao/p/12208923.html
Copyright © 2011-2022 走看看