Python執行緒條件變數Condition原理解析
阿新 • • 發佈:2020-01-20
這篇文章主要介紹了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',state)) pd = threading.Thread(name='producer',target=producer,)) cs1.start() time.sleep(2) #cs2.start() #time.sleep(2) pd.start()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。