生产者与消费者-条件变量
演示条件变量同步的经典问题是生产者与消费者问题:假设有一群生产者(Producer)和一群消费者(Consumer)通过一个市场来交互产品。生产者的”策略“是如果市场上剩余的产品少于1000个,那么就生产100个产品放到市场上;而消费者的”策略“是如果市场上剩余产品的数量多余100个,那么就消费3个产品。用Condition解决生产者与消费者问题的代码如下:
import threading
import time
class Producer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count > 1000:
con.wait()
else:
count += 100
msg = self.name+' produce 100, count=' + str(count)
print msg
con.notify()
con.release()
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count < 100:
con.wait()
else:
count -= 3
msg = self.name+' consume 3, count='+str(count)
print msg
con.notify()
con.release()
time.sleep(1)
if __name__ == '__main__':
count = 500
con = threading.Condition()
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()