zoukankan      html  css  js  c++  java
  • 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分钟呢?

  • 相关阅读:
    解题报告:POJ1852 Ants
    解题报告:POJ2573 Bridge(分析建模)
    POJ 3321 Apple Tree(树状数组模板)
    PAT1139 First Contact
    POJ3259 SPFA判定负环
    HDOJ2586 最近公共祖先模板
    树的直径与最近公共祖先
    字符数组_随机存储
    青鸟资料下载
    软件测试(4)_LoadRunner使用
  • 原文地址:https://www.cnblogs.com/nerdlerss/p/5836133.html
Copyright © 2011-2022 走看看