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

python條件變量之生產(chǎn)者與消費(fèi)者操作實(shí)例分析

 更新時(shí)間:2017年03月22日 11:39:04   作者:聰明的狐貍  
這篇文章主要介紹了python條件變量之生產(chǎn)者與消費(fèi)者操作,結(jié)合具體實(shí)例形式分析了Python條件變量的概念、原理、及線程操作的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了python條件變量之生產(chǎn)者與消費(fèi)者操作。分享給大家供大家參考,具體如下:

互斥鎖是最簡單的線程同步機(jī)制,面對復(fù)雜線程同步問題,Python還提供了Condition對象。Condition被稱為條件變量,除了提供與Lock類似的acquire和release方法外,還提供了wait和notify方法。線程首先acquire一個(gè)條件變量,然后判斷一些條件。如果條件不滿足則wait;如果條件滿足,進(jìn)行一些處理改變條件后,通過notify方法通知其他線程,其他處于wait狀態(tài)的線程接到通知后會重新判斷條件。不斷的重復(fù)這一過程,從而解決復(fù)雜的同步問題。

可以認(rèn)為Condition對象維護(hù)了一個(gè)鎖(Lock/RLock)和一個(gè)waiting池。線程通過acquire獲得Condition對象,當(dāng)調(diào)用wait方法時(shí),線程會釋放Condition內(nèi)部的鎖并進(jìn)入blocked狀態(tài),(但實(shí)際上不會block當(dāng)前線程)同時(shí)在waiting池中記錄這個(gè)線程。當(dāng)調(diào)用notify方法時(shí),Condition對象會從waiting池中挑選一個(gè)線程,通知其調(diào)用acquire方法嘗試取到鎖。

Condition對象的構(gòu)造函數(shù)可以接受一個(gè)Lock/RLock對象作為參數(shù),如果沒有指定,則Condition對象會在內(nèi)部自行創(chuàng)建一個(gè)RLock。

線程同步經(jīng)典問題----生產(chǎn)者與消費(fèi)者問題可以使用條件變量輕松解決。

import threading
import time
class Producer(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
  def run(self):
    global count
    while True:
      con.acquire()
      if count <20:
        count += 1
        print self.name," Producer product 1,current is %d" %(count)
        con.notify()
      else:
        print self.name,"Producer say box is full"
        con.wait()
      con.release()
      time.sleep(1)
class Consumer(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
  def run(self):
    global count
    while True:
      con.acquire()
      if count>4:
        count -=4
        print self.name,"Consumer consume 4,current is %d" %(count)
        con.notify()
      else:
        con.wait()
        print self.name," Consumer say box is empty"
      con.release()
      time.sleep(1)
count = 0
con = threading.Condition()
def test():
  for i in range(1):
    a = Consumer()
    a.start()
  for i in range(1):
    b =Producer()
    b.start()
if __name__=='__main__':
  test()

上面的代碼假定消費(fèi)者消費(fèi)的比較快,輸出結(jié)果為:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python Socket編程技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論