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

    1、程序中有两类角色,产生数据,消费数据

    2、解决问题是解决程序解偶合,平衡生产者和消费者之间的速度差

    from multiprocessing import Process,Queue
    import time
    def producer(q):
        for i in range(3):
            res="包子%s" % i
            time.sleep(1)
            q.put(res)
            print("生产者生产了%s" % res)
    def consumer(q):
        while True:
            time.sleep(1)
            res=q.get()
            if res==None:
                break
            print("消费者吃了%s" % res)
    
    if __name__ == "__main__":
        q=Queue()
        p=Process(target=producer,args=(q,))
        c = Process(target=consumer, args=(q,))
        p.start()
        c.start()
        p.join()
        q.put(None)
        print("主线程")

     JoinableQueue

    from multiprocessing import Process,Queue,JoinableQueue
    import time
    def producer(q):
        for i in range(3):
            res="包子%s" % i
            time.sleep(1)
            q.put(res)
            print("生产者生产了%s" % res)
        q.join()
    def consumer(q):
        while True:
            time.sleep(1)
            res=q.get()
            if res==None:
                break
            print("消费者吃了%s" % res)
            q.task_done()
    if __name__ == "__main__":
        q=JoinableQueue()
        p=Process(target=producer,args=(q,))
        c = Process(target=consumer, args=(q,))
        p.start()
        c.start()
        print("主线程")
  • 相关阅读:
    hdu5728 PowMod
    CF1156E Special Segments of Permutation
    CF1182E Product Oriented Recurrence
    CF1082E Increasing Frequency
    CF623B Array GCD
    CF1168B Good Triple
    CF1175E Minimal Segment Cover
    php 正则
    windows 下安装composer
    windows apache "The requested operation has failed" 启动失败
  • 原文地址:https://www.cnblogs.com/yaya625202/p/9030484.html
Copyright © 2011-2022 走看看