zoukankan      html  css  js  c++  java
  • 生产者以及消费者模式(进程池)

    code
    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()
     
        producterPool = Pool(3)
        for n in range(1, 21):
            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')
     
     
     
     
     
     

  • 相关阅读:
    框架集。样式表
    2017.11.23知识点整理
    HTML5的标签
    HTML5大体概括截图
    2017.11.21 通用标签及属性
    2017.11.21 课程随记
    JavaScript数组
    JavaScript语句
    javascript基础知识
    不用alert提示的非空表单验证
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14193366.html
Copyright © 2011-2022 走看看