本文實例講述了python條件變量之生產(chǎn)者與消費者操作。分享給大家供大家參考,具體如下:
互斥鎖是最簡單的線程同步機制,面對復(fù)雜線程同步問題,Python還提供了Condition對象。Condition被稱為條件變量,除了提供與Lock類似的acquire和release方法外,還提供了wait和notify方法。線程首先acquire一個條件變量,然后判斷一些條件。如果條件不滿足則wait;如果條件滿足,進(jìn)行一些處理改變條件后,通過notify方法通知其他線程,其他處于wait狀態(tài)的線程接到通知后會重新判斷條件。不斷的重復(fù)這一過程,從而解決復(fù)雜的同步問題。
可以認(rèn)為Condition對象維護(hù)了一個鎖(Lock/RLock)和一個waiting池。線程通過acquire獲得Condition對象,當(dāng)調(diào)用wait方法時,線程會釋放Condition內(nèi)部的鎖并進(jìn)入blocked狀態(tài),(但實際上不會block當(dāng)前線程)同時在waiting池中記錄這個線程。當(dāng)調(diào)用notify方法時,Condition對象會從waiting池中挑選一個線程,通知其調(diào)用acquire方法嘗試取到鎖。
Condition對象的構(gòu)造函數(shù)可以接受一個Lock/RLock對象作為參數(shù),如果沒有指定,則Condition對象會在內(nèi)部自行創(chuàng)建一個RLock。
線程同步經(jīng)典問題----生產(chǎn)者與消費者問題可以使用條件變量輕松解決。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
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() |
上面的代碼假定消費者消費的比較快,輸出結(jié)果為:
希望本文所述對大家Python程序設(shè)計有所幫助。