zoukankan      html  css  js  c++  java
  • 生产消费者模型代码示例

    import time
    import random
    from multiprocessing import Process,Queue
    def producer(q,name,food):
        for i in range(4):
            time.sleep(random.random())
            f = "{}生产出一个{}".format(name,food)
            print(f)
            q.put(f)
    def consumer(q,name):
        while True:
            food = q.get()
            if food is None:
                print("{}获取空,退出".format(name))
                break
            time.sleep(random.random())
            print("{}消费了一个{}".format(name,food))
    
    if __name__ == '__main__':
        q = Queue(10)
        p1 = Process(target=producer,args=(q,"生产者1号","包子"))
        p2 = Process(target=producer,args=(q,"生产者2号","馒头"))
        c1 = Process(target=consumer,args=(q,"消费者1号"))
        c2 = Process(target=consumer,args=(q,"消费者2号"))
        c3 = Process(target=consumer,args=(q,"消费者3号"))
        p1.start()
        p2.start()
        c1.start()
        c2.start()
        c3.start()
        p1.join()
        p2.join()
        q.put(None)
        q.put(None)
        q.put(None)
    View Code
    import time
    import random
    from multiprocessing import Process,JoinableQueue
    def producer(q,name,food):
        for i in range(4):
            time.sleep(random.random())
            f = "{}生产出一个{}".format(name,food)
            print(f)
            q.put(f)
        q.join()   #生产周期变长,要等到所生产的数据被处理完,这个子进程才结束
    def consumer(q,name):
        while True:
            food = q.get()
            time.sleep(random.random())
            print("{}消费了一个{}".format(name,food))
            q.task_done()
    
    if __name__ == '__main__':
        q = JoinableQueue(10)
        p1 = Process(target=producer,args=(q,"生产者1号","包子"))
        p2 = Process(target=producer,args=(q,"生产者2号","馒头"))
        c1 = Process(target=consumer,args=(q,"消费者1号"))
        c2 = Process(target=consumer,args=(q,"消费者2号"))
        c3 = Process(target=consumer,args=(q,"消费者3号"))
        p1.start()
        p2.start()
        c1.daemon = True  #设置为守护进程,主进程中的代码执行完毕之后,该守护进程自动结束
        c2.daemon = True
        c3.daemon = True
        c1.start()
        c2.start()
        c3.start()
        p1.join()   #感知一个进程的结束
        p2.join()
    View Code
  • 相关阅读:
    取消PHPCMS V9后台新版本升级提示信息
    phpcmsv9全站搜索,不限模型
    jq瀑布流代码
    phpcms v9模版调用代码
    angular.js添加自定义服务依赖项方法
    angular多页面切换传递参数
    angular路由最基本的实例---简单易懂
    作用域事件传播
    利用angular控制元素的显示和隐藏
    利用angular给节点添加样式
  • 原文地址:https://www.cnblogs.com/superniao/p/10123168.html
Copyright © 2011-2022 走看看