python-实现生产者消费者模型

生产者消费者:包子铺不停的做包子,行人不停的买 ---> 这样就达到了目的--->包子的销售 

两个不同的角色 包子铺,行人 只负责单一操作 让包子变成连接的介质.

 

 1 #_*_coding:utf-8_*_
 2 from threading import Thread
 3 from Queue import Queue
 4 import time
 5 class Procuder(Thread):
 6     def __init__(self,name,queue):
 7         self.__Name = name
 8         self.__Queue = queue
 9         super(Procuder,self).__init__()
10     def run(self):
11         while 1:
12             if self.__Queue.full():
13                 time.sleep(3)
14             else:
15                 time.sleep(1)
16                 self.__Queue.put('**star**')
17                 print '-->%s plus a star' % self.__Name
18 class Cunsumer(Thread):
19     def __init__(self,name,queue):
20         self.__Name = name
21         self.__Queue = queue
22         super(Cunsumer,self).__init__()
23     def run(self):
24          while 1:
25              if self.__Queue.empty():
26                     time.sleep(3)
27              else:
28                  time.sleep(1)
29                  self.__Queue.get()
30                  print '-->%s get a star' % self.__Name
31 maxque = Queue(maxsize=50)
32 
33 P1 = Procuder('p1',maxque)
34 P1.start()
35 P2 = Procuder('p2',maxque)
36 P2.start()
37 P3 = Procuder('p3',maxque)
38 P3.start()
39 for i in range(20):
40     print '_________________'
41     temp = Cunsumer(i,maxque)
42     temp.start()

 于是问题来了 --->为什么我们需要这个模型?

1解耦:核心就是把生产者和消费者两个对象关系变得不紧密了

2缓冲:如果你是快递员,送一栋人很多的楼,你觉得是一个个的送,还是送到前台,发个短信让他们自己来拿好呢?

3防止阻塞:还是上面的例子,如果你是一个个的送 那么如果有个人 30分钟才会取 你是不是要等30分钟呢?

posted @ 2016-09-03 04:03  nerdlerss  阅读(639)  评论(0编辑  收藏  举报