美文网首页
Python46_利用生产者与消费者模式解决耦合问题

Python46_利用生产者与消费者模式解决耦合问题

作者: jxvl假装 | 来源:发表于2019-09-28 10:56 被阅读0次

    队列:先进先出(FIFO:first in first out)

    栈:先进后出(FILO:firt in last out)

    用队列实现生产者与消费者问题的代码如下:

    import threading
    import time
    from queue import Queue
    
    
    class Producer(threading.Thread):
        def run(self):
            global queue
            count = 0
            while True:
                if queue.qsize() < 1000:    #满足某个条件:生产
                    for i in range(100):
                        count += 1
                        msg = "生成产品" + str(i)
                        queue.put(msg)
                        print(msg)
                time.sleep(0.5)
    
    
    class Consumer(threading.Thread):
        def run(self):
            global queue
            while True:
                if queue.qsize() > 100: #满足某个条件,消费
                    for i in range(3):
                        msg = self.name + " 消费了 " + queue.get()
                        print(msg)
                    time.sleep(1)
    
    if __name__ == "__main__":
        queue = Queue()
        for i in range(500):
            queue.put("初始产品 {}".format(i))
    
        for i in range(2):  #创建两个生产者
            p = Producer()
            p.start()
    
        for i in range(5):  #创建5个消费者
            c = Consumer()
            c.start()
    

    相关文章

      网友评论

          本文标题:Python46_利用生产者与消费者模式解决耦合问题

          本文链接:https://www.haomeiwen.com/subject/tghuuctx.html