zoukankan      html  css  js  c++  java
  • 生产者消费模型

    '''为什么要使用生产者消费者模型

    生产者指的是生产数据的任务,消费者指的是处理数据的任务,在并发编程中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。

    什么是生产者和消费者模式

    生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。

    这个阻塞队列就是用来给生产者和消费者解耦的'''
    from multiprocessing import Process, Queue
    import time
    def producer(q):
    for i in range(10):
    res = '包子%s'%i
    time.sleep(0.5)
    print('生产者生产了%s'%i)
    q.put(res)
    def consmer(q):
    while True:
    res = q.get()
    if res is None:break
    time.sleep(1)
    print('消费者吃了%s'%res)
    if __name__ == '__main__':
    q = Queue()
    p1 = Process(target=producer, args=(q,))
    p2 = Process(target=producer, args=(q,))
    p3 = Process(target=producer, args=(q,))
    c1 = Process(target=consmer, args=(q,))
    c2 = Process(target=consmer, args=(q,))
    p1.start()
    p2.start()
    p3.start()
    c1.start()
    c2.start()
    p1.join()
    #c1.join()
    q.put(None)
    print('主')

    '''此时的问题是主进程永远不会结束,原因是:生产者p在生产完后就结束了,但是消费者c在取空了q之后,则一直处于死循环中且卡在q.get()
    这一步。

    解决方式无非是让生产者在生产完毕后,往队列中再发一个结束信号,这样消费者在接收到结束信号后就可以break出死循环
    '''



  • 相关阅读:
    IDA .edata .rdata .idata .text segments
    How to detect the types of executable files
    Dynamic-Link Library Redirection
    J-Link Version
    PE文件结构部分解析以及输入的定位
    Delphi : Analyze PE file headers?
    How to tell if a file is an EXE or a DLL?
    PE Header and Export Table for Delphi
    NXP ARM Vector Table CheckSum
    反接保护电路 Reverse Voltage Protection
  • 原文地址:https://www.cnblogs.com/yuexijun/p/11521724.html
Copyright © 2011-2022 走看看