zoukankan      html  css  js  c++  java
  • 队列 Queue 与 生产者消费模型

    队列:先进先出

    # from multiprocessing import  Queue
    # Q = Queue(4)
    
    # Q.put('a')
    # Q.put('b')
    # Q.put('b')
    # Q.put('c')
    
    # print(Q.get())
    # print(Q.get())
    # print(Q.get())
    # print(Q.get())
    View Code
    生产者消费模型
    from multiprocessing import Process,Queue
    import random,time
    
    def product(name,food,Q):
        for i in range(3):
            res = '%s %s'%(food,i)
            Q.put(res)
            time.sleep(random.randint(1,3))
            print('%s 生产了 %s' %(name,res))
    
    def consumer(name,Q):
        while True:
            res = Q.get()
            if res is None:break
            time.sleep(random.randint(1,3))
            print('%s 吃了 %s' % (name, res))
    
    if __name__ == '__main__':
        Q = Queue()
        p1 = Process(target=product,args=('wxx','包子',Q))   # 生产者
        p2 = Process(target=product, args=('yxx', '馒头', Q))  # 生产者
        p3 = Process(target=product, args=('zxx', '粉丝', Q))  # 生产者
    
        c1 = Process(target=consumer,args=('axx',Q))  # 消费者
        c2 = Process(target=consumer, args=('bxx', Q))  # 消费者
    
        p1.start()
        p2.start()
        p3.start()
    
        c1.start()
        c2.start()
    
        p1.join()
        p2.join()
        p3.join()
    
        Q.put(None)
        Q.put(None)
    
        print('主...')
    模型1
    from multiprocessing import Process,JoinableQueue
    import random,time

    def product(name,food,Q):
    for i in range(3):
    res = '%s %s'%(food,i)
    Q.put(res)
    time.sleep(random.randint(1,3))
    print('%s 生产了 %s' %(name,res))

    def consumer(name,Q):
    while True:
    res = Q.get()
    time.sleep(random.randint(1,3))
    print('%s 吃了 %s' % (name, res))
    Q.task_done() # 队列取完信号

    if __name__ == '__main__':
    Q = JoinableQueue() # 队列链接
    p1 = Process(target=product,args=('wxx','包子',Q)) # 生产者
    p2 = Process(target=product, args=('yxx', '馒头', Q)) # 生产者
    p3 = Process(target=product, args=('zxx', '粉丝', Q)) # 生产者

    c1 = Process(target=consumer,args=('axx',Q)) # 消费者
    c2 = Process(target=consumer, args=('bxx', Q)) # 消费者

    c1.daemon = True
    c2.daemon = True

    p1.start()
    p2.start()
    p3.start()

    c1.start()
    c2.start()

    p1.join()
    p2.join()
    p3.join() # 保证生产者生产完

    Q.join() # 保证队列取完

    print('主...')
  • 相关阅读:
    perl练习——FASTA格式文件中序列GC含量计算&perl数组排序如何获得下标或者键
    短序列组装Sequence Assembly(转载)
    MEGA软件——系统发育树构建方法(图文讲解) 转载
    R语言中的read.table()
    网络七层模型OSI(Open System Interconnection)
    MySQL报错“The server time zone value '�й���׼ʱ��' is unrecognized”
    JDK环境变量配置
    netstat命令
    敏捷方法论(Agile Methodologies)
    0 upgraded, 0 newly installed, 0 to remove and 6 not upgraded解决方法
  • 原文地址:https://www.cnblogs.com/liu--huan/p/9598592.html
Copyright © 2011-2022 走看看