当前位置: 首页 > news >正文

什么时候会用到 concurrent.futures?要不要背?

什么时候会用到 concurrent.futures?要不要背?

    • 一、到底什么时候会用到它?
    • 二、哪些 API 必须背下来?
      • 1. 创建线程池:`ThreadPoolExecutor`
      • 2. 提交单个任务:`submit()` + `Future`
      • 3. 等最快先完成:`as_completed()`
      • 4. 统一收集结果(顺序固定):`executor.map()`
      • 5. 任务完成后自动回调:`add_done_callback()`
      • 6. 取消任务:`cancel()`
      • 7. CPU 密集场景换进程池:`ProcessPoolExecutor`
    • 三、易踩的坑(背下来少加班)
    • 四、总结背诵清单


一、到底什么时候会用到它?

场景举例是否必须掌握
IO 密集型并发同时爬 100 个网页、并发下载、并发调用第三方 API✅ 推荐掌握
CPU 密集型并行图像批量压缩、科学计算(NumPy 之外的部分)✅ 推荐掌握
简化 Thread/Process 手写不想手动写 threading.Threadmultiprocessing.Process✅ 推荐掌握
异步回调需求任务完成后自动写日志、发通知✅ 推荐掌握
需要超时/取消任务爬虫里 3 秒还没下完就放弃✅ 推荐掌握

一句话:只要你写过“for 循环逐个处理,太慢!”就值得用 concurrent.futures 来提速/简化代码。


二、哪些 API 必须背下来?

下面把真正常用、面试常问、开发必会的 7 个核心点提炼出来,并给出最小可运行示例。
复制即可跑,建议收藏+背诵。


1. 创建线程池:ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor
import requestsURLS = ["https://www.baidu.com","https://www.zhihu.com","https://www.bilibili.com",
]def fetch(url):return requests.get(url, timeout=5).status_code# ===== 背:最常用的 3 行 =====
with ThreadPoolExecutor(max_workers=3) as pool:for status in pool.map(fetch, URLS):print(status)

2. 提交单个任务:submit() + Future

from concurrent.futures import ThreadPoolExecutorpool = ThreadPoolExecutor()
future = pool.submit(pow, 2, 10)   # 2**10
print(future.result())             # 1024
pool.shutdown()                    # 别忘了,或用 with

3. 等最快先完成:as_completed()

from concurrent.futures import ThreadPoolExecutor, as_completed
import time, randomdef work(x):time.sleep(random.random())return x * xwith ThreadPoolExecutor() as pool:futures = [pool.submit(work, i) for i in range(5)]for f in as_completed(futures):         # 谁先完就处理谁print(f"done: {f.result()}")

4. 统一收集结果(顺序固定):executor.map()

with ThreadPoolExecutor() as pool:squares = list(pool.map(lambda x: x**2, range(5)))
print(squares)   # [0, 1, 4, 9, 16] 顺序与输入一致

5. 任务完成后自动回调:add_done_callback()

def callback(fut):print("Task finished, result =", fut.result())with ThreadPoolExecutor() as pool:f = pool.submit(lambda: 42)f.add_done_callback(callback)

6. 取消任务:cancel()

with ThreadPoolExecutor(max_workers=2) as pool:future = pool.submit(time.sleep, 10)print("cancel success?", future.cancel())  # True/False

7. CPU 密集场景换进程池:ProcessPoolExecutor

from concurrent.futures import ProcessPoolExecutor
import mathdef is_prime(n):return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))with ProcessPoolExecutor() as pool:primes = list(pool.map(is_prime, range(100)))
print(sum(primes))  # 25

三、易踩的坑(背下来少加班)

解决口诀
全局变量在进程池不共享传参、队列或 multiprocessing.Manager
进程池里抛异常会 Brokentry/except BrokenProcessPool
submitshutdownwith ThreadPoolExecutor() as ex:

四、总结背诵清单

  1. 线程池ThreadPoolExecutor(max_workers=n)
  2. 进程池ProcessPoolExecutor(max_workers=n)
  3. 批量 mapexecutor.map(func, iterable) → 顺序固定
  4. 单个 submitfuture = executor.submit(func, *args)
  5. 谁先完成for f in as_completed(futures): ...
  6. 回调future.add_done_callback(fn)
  7. 取消future.cancel()
  8. 异常future.exception() / try...except BrokenProcessPool
  9. 上下文管理with executor: 自动 shutdown
http://www.dtcms.com/a/276954.html

相关文章:

  • 【Linux | 网络】应用层
  • 003_了解Claude
  • 基于SpringBoot3集成Kafka集群
  • MongoDB性能优化实战指南:原理、实践与案例
  • 【设计模式】职责链模式(责任链模式) 行为型模式,纯与不纯的职责链模式
  • 前端框架状态管理对比:Redux、MobX、Vuex 等的优劣与选择
  • ALB、NLB、CLB 负载均衡深度剖析
  • 闲庭信步使用图像验证平台加速FPGA的开发:第十二课——图像增强的FPGA实现
  • axios拦截器
  • spring cloud负载均衡分析之FeignBlockingLoadBalancerClient、BlockingLoadBalancerClient
  • 【Qt开发】Qt的背景介绍(一)
  • 时序预测 | Matlab代码实现VMD-TCN-GRU-MATT变分模态分解时间卷积门控循环单元多头注意力多变量时序预测
  • [特殊字符] Python自动化办公 | 3步实现Excel数据清洗与可视化,效率提升300%
  • 开源链动2+1模式、AI智能名片与S2B2C商城小程序在私域运营中的协同创新研究
  • 从零开始跑通3DGS教程:(五)3DGS训练
  • 《区间dp》
  • 一文读懂现代卷积神经网络—深度卷积神经网络(AlexNet)
  • 深入理解观察者模式:构建松耦合的交互系统
  • Redis技术笔记-从三大缓存问题到高可用集群落地实战
  • ESP-Timer入门(基于ESP-IDF-5.4)
  • JVM:内存、类加载与垃圾回收
  • 每天一个前端小知识 Day 30 - 前端文件处理与浏览器存储机制实践
  • [Rust 基础课程]选一个合适的 Rust 编辑器
  • 通用定时器GPT
  • 输入npm install后发生了什么
  • # 通过wifi共享打印机只有手动翻页正反打印没有自动翻页正反打印,而通过网线连接的主机电脑可以自动翻页正反打印
  • OneCode3.0 VFS分布式文件管理API速查手册
  • Codeforces Round 855 (Div. 3)
  • 【iOS】方法与消息底层分析
  • 动物世界一语乾坤韵芳华 人工智能应用大学毕业论文 -仙界AI——仙盟创梦IDE