concurrent库学习之ThreadPoolExecutor模块

concurrent库学习之ThreadPoolExecutor模块

一、简介

concurrent.futures.ThreadPoolExecutor 是 Python 标准库中的一个模块,用于管理线程池并行执行任务。它提供了一种高层次的接口来启动和管理线程,简化了并发编程的复杂性。

二、语法和参数

语法
python 复制代码
concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
参数
  • max_workers:线程池中允许的最大线程数。如果为 None 或未指定,则默认值为 os.cpu_count() * 5
  • thread_name_prefix:线程名称的前缀,用于标识线程。
  • initializer:每个工作线程在启动时调用的可调用对象。
  • initargs:传递给 initializer 的参数元组。

三、实例

3.1 使用线程池执行简单任务
  • 代码
python 复制代码
import concurrent.futures
import time

def task(n):
    print(f"Task {n} is running")
    time.sleep(2)
    return f"Task {n} completed"

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(task, i) for i in range(5)]
    for future in concurrent.futures.as_completed(futures):
        print(future.result())
  • 输出

    Task 0 is running
    Task 1 is running
    Task 2 is running
    Task 3 is running
    Task 0 completed
    Task 4 is running
    Task 1 completed
    Task 2 completed
    Task 3 completed
    Task 4 completed

3.2 使用线程池执行带有返回值的任务
  • 代码
python 复制代码
import concurrent.futures

def square(n):
    return n * n

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(square, range(10)))
    print(results)
  • 输出

    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

四、注意事项

  1. ThreadPoolExecutor 适用于 I/O 密集型任务,而不是 CPU 密集型任务。对于 CPU 密集型任务,建议使用 ProcessPoolExecutor
  2. 确保正确管理线程池的生命周期,使用 with 语句可以自动管理资源。
  3. 在提交大量任务时,注意控制 max_workers 的数量,以避免线程过多导致系统资源耗尽。
  4. 使用 concurrent.futures.as_completed 可以按完成顺序获取任务结果,而不是提交顺序。

相关推荐
程序员杰哥20 小时前
Python自动化测试之线上流量回放:录制、打标、压测与平台选择
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
吴佳浩20 小时前
LangChain v1 重大更新讲解⚠⚠⚠
python·langchain·agent
智商低情商凑1 天前
Go学习之 - Goroutines和channels
开发语言·学习·golang
顾安r1 天前
11.20 开源APP
服务器·前端·javascript·python·css3
敲敲了个代码1 天前
CSS 像素≠物理像素:0.5px 效果的核心密码是什么?
前端·javascript·css·学习·面试
萧鼎1 天前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
没有bug.的程序员1 天前
Java 字节码:看懂 JVM 的“机器语言“
java·jvm·python·spring·微服务
CappuccinoRose1 天前
MATLAB学习文档(二十八)
开发语言·学习·算法·matlab
下午见。1 天前
Python基础入门:用Anaconda搭建环境的启蒙之旅
python
('-')1 天前
《从根上理解MySQL是怎样运行的》第四章学习笔记
笔记·学习·mysql