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 可以按完成顺序获取任务结果,而不是提交顺序。

相关推荐
用户0332126663672 小时前
使用 Python 设置 Excel 文件属性
python
JoannaJuanCV2 小时前
VLM学习-DINOv2论文解读
学习
jyOverQ2 小时前
LangGraph Agent 模式详解:从自主决策到 Tool Calling 执行链
python·langchain
青 春 记 忆2 小时前
LeetCode 226. 翻转二叉树|Python 解法详解
python·算法·leetcode
小女孩真可爱2 小时前
GPT(1)----------从零实现 GPT 模型以生成文本
人工智能·python·gpt·nlp
码云骑士2 小时前
116-Python调用GPT-4V分析图片-Base64编码-多图-JSON结构化输出
开发语言·python·json
超爱西西鸭2 小时前
ArkTS延安精神学习应用:四版块 + 三组展开状态 + 大事记时间轴
学习·华为·harmonyos·鸿蒙
老郑聊AI业财智造2 小时前
TensorFlow 技术架构与源码分析
人工智能·python·深度学习·架构·tensorflow·软件工程
民乐团扒谱机2 小时前
【微科普】压缩感知(CS):违反了奈奎斯特采样定理?不先采集也能还原信号?大白话讲透稀疏采样、L1重建与OMP,一文吃透附代码
python·神经网络·线性代数·算法·数学建模·压缩感知·奈奎斯特
m4Rk_2 小时前
【论文阅读】Agent 记忆机制(49):MemCoE——先学习如何组织记忆,再学习具体记住什么
论文阅读·人工智能·学习·开源·github