首页 > 代码库 > python-生产者消费者模式

python-生产者消费者模式

 1 #!/usr/bin/python
 2 #coding=utf-8
 3 
 4 import threading,time
 5 lock=threading.Condition()
 6 product=0
 7 class Make(threading.Thread):
 8     def __init__(self,lock):
 9         self.lock=lock
10         super(Make,self).__init__()
11 
12     def run(self):
13         global product
14         while 1:
15             if self.lock.acquire():
16                 if product>=1000:
17                     self.lock.wait()
18                 else:
19                     product+=100
20                     print "add 100,product count="+str(product)
21                     self.lock.notify()
22                 self.lock.release()
23                 time.sleep(2)
24 
25 class Cost(threading.Thread):
26     def __init__(self,lock):
27         self.lock=lock
28         super(Cost,self).__init__()
29 
30     def run(self):
31         global product
32         while 1:
33             if self.lock.acquire():
34                 if product<=100:
35                     self.lock.wait()
36                 else:
37                     product-=60
38                     print "cost 60,product count="+str(product)
39                     self.lock.notify()
40                 self.lock.release()
41                 time.sleep(1)
42 
43 def test():
44     for i in range(5):
45         n=Make(lock)
46         n.start()
47     for i in range(5):
48         m=Cost(lock)
49         m.start()
50 if __name__=="__main__":
51     test()

 

python-生产者消费者模式