您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python線程條件變量Condition原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下 |
這篇文章主要介紹了Python線程條件變量Condition原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
Condition 對(duì)象就是條件變量,它總是與某種鎖相關(guān)聯(lián),可以是外部傳入的鎖或是系統(tǒng)默認(rèn)創(chuàng)建的鎖。當(dāng)幾個(gè)條件變量共享一個(gè)鎖時(shí),你就應(yīng)該自己傳入一個(gè)鎖。這個(gè)鎖不需要你操心,Condition 類(lèi)會(huì)管理它。
acquire() 和 release() 可以操控這個(gè)相關(guān)聯(lián)的鎖。其他的方法都必須在這個(gè)鎖被鎖上的情況下使用。wait() 會(huì)釋放這個(gè)鎖,阻塞本線程直到其他線程通過(guò) notify() 或 notify_all() 來(lái)喚醒它。一旦被喚醒,這個(gè)鎖又被 wait() 鎖上。
經(jīng)典的 consumer/producer 問(wèn)題的代碼示例為:
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()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助
原文地址: https://www.linuxprobe.com/python-condition-parsing.html
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。