1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import threading 5 import random, time, Queue 6 7 MAX_SIZE = 5 8 SHARE_Q = [] #模拟共享队列 9 CONDITION = threading.Condition() 10 11 class Producer(threading.Thread) : 12 13 def run(self) : 14 products = range(5) 15 global SHARE_Q 16 while True : 17 CONDITION.acquire() 18 if len(SHARE_Q) == 5 : 19 print "Queue is full.." 20 CONDITION.wait() 21 print "Consumer have comsumed something" 22 product = random.choice(products) 23 SHARE_Q.append(product) 24 print "Producer : ", product 25 CONDITION.notify() 26 CONDITION.release() 27 time.sleep(random.random()) 28 29 class Consumer(threading.Thread) : 30 31 def run(self) : 32 global SHARE_Q 33 while True: 34 CONDITION.acquire() 35 if not SHARE_Q : 36 print "Queue is Empty..." 37 CONDITION.wait() 38 print "Producer have producted something" 39 product = SHARE_Q.pop(0) 40 print "Consumer :", product 41 CONDITION.notify() 42 CONDITION.release() 43 time.sleep(random.random()) 44 45 def main() : 46 producer = Producer() 47 consumer = Consumer() 48 producer.start() 49 consumer.start() 50 51 if __name__ == '__main__': 52 main()
Condition
条件变量中有acquire()和release方法用来调用锁的方法
, 有wait(), notify(), notifyAll()方法
, 后面是三个方法必须在获取锁的情况下调用, 否则产生RuntimeError
错误.
- 当一个线程获得锁后, 发现没有期望的资源或者状态, 就会调用wait()阻塞, 并释放已经获得锁, 知道期望的资源或者状态发生改变
- 当一个线程获得锁, 改变了资源或者状态, 就会调用notify()和notifyAll()去通知其他线程,