欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python線程條件變量Condition原理解析

 更新時間:2020年01月20日 10:10:28   作者:虛生  
這篇文章主要介紹了Python線程條件變量Condition原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

這篇文章主要介紹了Python線程條件變量Condition原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

Condition 對象就是條件變量,它總是與某種鎖相關(guān)聯(lián),可以是外部傳入的鎖或是系統(tǒng)默認(rèn)創(chuàng)建的鎖。當(dāng)幾個條件變量共享一個鎖時,你就應(yīng)該自己傳入一個鎖。這個鎖不需要你操心,Condition 類會管理它。

acquire() 和 release() 可以操控這個相關(guān)聯(lián)的鎖。其他的方法都必須在這個鎖被鎖上的情況下使用。wait() 會釋放這個鎖,阻塞本線程直到其他線程通過 notify() 或 notify_all() 來喚醒它。一旦被喚醒,這個鎖又被 wait() 鎖上。

經(jīng)典的 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()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論