You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中func1、func2应用threading与multiprocessing的最简实现方法

最简实现方案

直接用Python标准库concurrent.futures即可,所有场景的写法和你偏好的multiprocessing.Pool风格完全一致,仅需少量代码。

注意:不要使用list作为变量名,会覆盖Python内置类,以下示例统一替换为items_list。


1. func1的多线程(threading)实现

func1无返回值,直接提交执行即可:

from concurrent.futures import ThreadPoolExecutor

# 可根据任务类型调整max_workers,IO密集型任务可设为CPU核心数的2~4倍
with ThreadPoolExecutor(max_workers=6) as executor:
    executor.map(func1, items_list)

2. func2的多线程(threading)实现

func2有返回值,直接将map的迭代器转为列表即可拿到结果集:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=6) as executor:
    result_list = list(executor.map(func2, items_list))

3. func2的多进程(multiprocessing)实现

写法和多线程完全一致,仅需替换执行器类:

from concurrent.futures import ProcessPoolExecutor

# 多进程的max_workers建议和CPU核心数保持一致,避免过高的上下文切换开销
with ProcessPoolExecutor(max_workers=6) as executor:
    result_list = list(executor.map(func2, items_list))

补充说明

  • 你之前用的multiprocessing.Pool写法也可以替换为统一的ProcessPoolExecutor风格,执行效果完全一致:
with ProcessPoolExecutor(max_workers=6) as executor:
    executor.map(func1, items_list)
  • 多进程场景要求传入的函数、参数都支持pickle序列化,这是Python多进程的常规限制。

内容的提问来源于stack exchange,提问作者Joesf.Albert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:54:04