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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM