条件变量是属于线程的高级应用,所以我们一般需要引入threading模块,而在条件变量中,最经典的例子,恐怕就是生产者与消费者的问题了。
Condition: 一个比Lock, RLock更高级的锁
wait: 等待被唤醒
notify/notifyAll : 唤醒一个线程,或者唤醒所有线程
注意:Condition,在wait之前必须require
代码:
1 import threading 2 import time 3 4 class Buf: 5 def __init__(self): 6 7 self.cond = threading.Condition() 8 self.data = [] 9 10 def isFull(self): 11 return len(self.data) == 5 12 13 def isEmpty(self): 14 return len(self.data) == 0 15 16 def get(self): 17 18 self.cond.acquire() 19 20 while self.isEmpty(): 21 self.cond.wait() 22 23 temp = self.data.pop(0) 24 25 self.cond.notify() 26 self.cond.release() 27 return temp 28 29 def put(self, putInfo): 30 self.cond.acquire() 31 32 while self.isFull(): 33 self.cond.wait() 34 35 self.data.append(putInfo) 36 37 self.cond.notify() 38 self.cond.release() 39 40 41 def Product(num): 42 for i in range(num): 43 info.put(i+1) 44 print "Product %s " % (str(i+1)) 45 46 def Customer(id, num): 47 for i in range(num): 48 temp = info.get() 49 print "Customer%s %s " % (id, str(temp)) 50 51 info = Buf(); 52 53 54 if __name__ == "__main__": 55 p = threading.Thread(target=Product, args=(10, )) 56 c1 = threading.Thread(target=Customer, args=('A', 5)) 57 c2 = threading.Thread(target=Customer, args=('B', 5)) 58 59 p.start() 60 time.sleep(1) 61 c1.start() 62 c2.start() 63 64 p.join() 65 c1.join() 66 c2.join() 67 68 print "Game Over"