首页 > 代码库 > 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-生产者消费者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。