码迷,mamicode.com
首页 > 编程语言 > 详细

python-生产者消费者模式

时间:2017-07-17 17:06:07      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:product   UI   global   main   color   name   class   threading   elf   

 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-生产者消费者模式

标签:product   UI   global   main   color   name   class   threading   elf   

原文地址:http://www.cnblogs.com/chengyunshen/p/7196005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!