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分钟呢?

  • 相关阅读:
    Vagrant安装virtualbox
    SQLSERVER排查CPU占用高的情况
    删除重复记录,只留一条
    ASCII码对应表chr(9)、chr(10)、chr(13)、chr(32)、chr(34)、chr(39)、……
    手机和PC端的录屏软件
    2017年初面试总结
    Python面向对象
    Python字体颜色
    Python第二模块总结
    Fiddler使用教程(转)
  • 原文地址:https://www.cnblogs.com/nerdlerss/p/5836133.html
Copyright © 2011-2022 走看看