zoukankan      html  css  js  c++  java
  • python concurrent.futures.Threadpoolexcutor的有界队列和无界队列

    1、默认是无界队列,如果生产任务的速度大大超过消费的速度,则会把生产任务无限添加到无界队列中,这样一来控制不了生产速度,二来是会造成系统内存会被队列中的元素堆积增多而耗尽。

    2、改写为有界队列

    class BoundedThreadPoolExecutor(ThreadPoolExecutor):
        def __init__(self, max_workers=None, thread_name_prefix=''):
            super().__init__(max_workers,thread_name_prefix)
            self._work_queue = queue.Queue(max_workers * 2)

    这个很容易测试验证,消费函数里面来加个time.sleep,如果使用ThreadPoolExecutor会一股脑生成任务添加到任务队列中,由于线程池同时处理不了那么多的任务,任务队列内存增大。

    如果使用BoundedThreadPoolExecutor,当任务队列中的任务是线程池最大线程数量的2倍后,则会被block住,不再继续生成任务,直到任务队列可以被put一个元素

    具体的测试方法可以用下面来测试

    def fun(i__):
        time.sleep(2)
        print(str(i__) + 'hi')
    
    
    
    # pool = BoundedThreadPoolExecutor(5)
    pool = ThreadPoolExecutor(5)
    for i in range(100):
        print(i)
        pool.submit(fun,i)

    如果使用ThreadPoolExecutor,会迅速打印0到99.然后慢慢打印 0hi 1hi 2hi   。。。。。。。。

    如果使用BoundedThreadPoolExecutor则会交替打印,不会一下子就迅速打印完0到99.

  • 相关阅读:
    子页面向父页面传值
    UEditor的使用方法
    MVC 生成PDf表格并插入图片
    简单行列转换记录
    此数据库没有有效所有者“的解决,我很受用
    ASP.NET MVC3 使用kindeditor编辑器获取不到值
    c#读写文件
    VB 中Sub和Function的区别
    问题集
    hadoop2.7.2运行例子时报错
  • 原文地址:https://www.cnblogs.com/ydf0509/p/9631806.html
Copyright © 2011-2022 走看看