前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python原生线程池ThreadPoolExecutor

Python原生线程池ThreadPoolExecutor

作者头像
Steve Wang
发布2021-12-20 18:48:58
5.5K0
发布2021-12-20 18:48:58
举报
文章被收录于专栏:从流域到海域从流域到海域

Python原生线程池

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

python多线程

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

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

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

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

Python原生线程池ThreadPoolExecutor

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

代码语言:javascript
复制
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接收两个参数,第一个参数指定线程数量,第二个参数指定这些线程名字的前缀。

运行结果如下:

代码语言:javascript
复制
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(),该方法将阻塞当前线程直到线程完成任务。

代码语言:javascript
复制
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语句来配合线程池来使用:

代码语言:javascript
复制
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方法。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-12-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python原生线程池
  • python多线程
  • Python原生线程池ThreadPoolExecutor
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档