zoukankan      html  css  js  c++  java
  • python生产者和消费者模式实现(三)进程池方式

    注意:如果要使用Pool(进程池方式)创建进程,就需要使用multiprocessing.Manager()中的 Queue(),而不是multiprocessing.Queue()

    import time
    import random
    from multiprocessing import Pool, Manager


    # 生产者
    def producer(q, i):
    food = 'Spam-%d' % i
    time.sleep(random.uniform(1, 2))
    timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print('时间:%s 生产者:%d 生产了 Spam-%d' % (timeVal, i, i))
    q.put(food)


    # 消费者
    def consumer(q, i):
    while True:
    food = q.get()
    if not food: break
    time.sleep(random.uniform(1, 2))
    timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print('时间:%s 消费者: %d 吃了 %s' % (timeVal, i, food))


    if __name__ == '__main__':
    q = Manager().Queue()

    producterNum = 50
    producterPoolNum = 5
    producterPool = Pool(producterPoolNum)
    for n in range(1, producterNum + 1):
    producterPool.apply_async(producer, (q, n))

    consumerPoolNum = 5
    consumerPool = Pool(consumerPoolNum)
    for n in range(1, consumerPoolNum + 1):
    consumerPool.apply_async(consumer, (q, n))

    producterPool.close()
    producterPool.join()

    for n in range(1, consumerPoolNum + 1):
    q.put(None)

    consumerPool.close()
    consumerPool.join()

    print('end')

  • 相关阅读:
    17. 文件查找
    18. 后台进程
    16. Linux 文件目录权限
    15. SSH 远程
    14. 用户管理
    Emacs Python 自动补全--Elpy
    C++ 程序在运行时不显示dos界面
    OpenCV设置摄像头分辨率及全屏显示
    #error : Xiron Platform Abstraction Layer
    Win10 下Cmake编译配置 Opencv3.1 + Cuda7.5 + VS2013
  • 原文地址:https://www.cnblogs.com/WebLinuxStudy/p/11776832.html
Copyright © 2011-2022 走看看