Python原生线程池ThreadPoolExecutor

注意:由于GIL,即全局解释器锁的存在,Python的多线程是伪多线程,能产生的并行程度有限,不如go或者java的多线程。但Python提供了多进程来提高并发。

Python原生线程池

多线程的基本知识这里就不再赘述了,本文只讲Python原生线程池的用法。

python多线程

Python3种多线程常用的两个模块为:

  • _thread (已废弃,不推荐)
  • threading (推荐)

使用线程有两种方式,函数式调用或者继承线程类来包装线程对象

但如果线程超过一定数量,这种方式将会变得很复杂且线程的开关开销线性递增。池化思想是一种工程上管理长期占用资源并使用提高其使用效率的常见思想,它的体现包括数据库连接池、线程池等等。池化思想非常直观,将要维护的资源保存在一个池子里,下一次请求到来时,如果池子里已经有可用资源,则直接返回可用资源;如果没有可用资源,则等待其他使用者使用完成后释放资源。

Python原生线程池ThreadPoolExecutor

Python原生的线程池来自concurrent.futures模块中的ThreadPoolExecutor(也有进程池ProcessPoolExecutor,本文仅关注线程池),它提供了简单易用的线程池创建和管理方法。

from concurrent.futures import ThreadPoolExecutor

def func(i):
    print(i)
    print("executed func")
    
thread_pool_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="test_")  # 第一个参数指定线程数量 第二个参数指定这些线程名字的前缀

for i in range(10):
    thread_pool_executor.submit(func, i)

thread_pool_executor.shutdown(wait=True)

ThreadPoolExecutor接收两个参数,第一个参数指定线程数量,第二个参数指定这些线程名字的前缀。

运行结果如下:

0
executed func
1
executed func
2
executed func
3
executed func
4
executed func
56
executed func
7
executed func
8
executed func
9
executed func

executed func

ThreadPoolExecutor.submit()方法将返回一个future对象,如果想要获得函数运行结果,可以使用future.result(),该方法将阻塞当前线程直到线程完成任务。这是一个踩坑点,如果使用了该方法,而线程运行的函数因存在偶发bug而不能够终止,将导致主线程无限期等待进程池里的子线程返回结果而阻塞

from concurrent.futures import ThreadPoolExecutor, as_completed

def func(i):
    print("executed func")
    return i
    
thread_pool_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="test_")

all_task = [thread_pool_executor.submit(func, i) for i in range(10)]

for future in as_completed(all_task):
    res = future.result()
    print("res", str(res))

thread_pool_executor.shutdown(wait=True)

as_completed()方法用于将线程池返回的future对象按照线程完成的顺序排列,不加也可以,不加则返回的顺序为按线程创建顺序返回

除此之外,还可以使用with语句来配合线程池来使用:

from concurrent.futures import ThreadPoolExecutor, as_completed

def func(i):
    print("executed func")
    return i
    

with ThreadPoolExecutor(max_workers=5, thread_name_prefix="test_") as thread_pool_executor:
    all_task = [thread_pool_executor.submit(func, i) for i in range(10)]

    for future in as_completed(all_task):
        res = future.result()
        print("res", str(res))

with语句将自动关闭线程池,也就是自动执行shutdown方法。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值