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

Mac系统下使用concurrent.futures.ProcessPoolExecutor报错求助

解决ProcessPoolExecutor在MacOS Python 3.8+中的RuntimeError问题

别担心,这不是Mac系统的问题,是你没遵循Python多进程在spawn启动模式下的代码规范。

Python 3.8及以后版本,MacOS上的multiprocessing模块默认把进程启动方式从fork改成了spawn(主要是为了更好地兼容系统框架和第三方库)。这种启动方式有个关键要求:所有执行多进程逻辑的代码必须放到if __name__ == '__main__':条件块中。

修正后的代码

from concurrent.futures import ProcessPoolExecutor

def foo(x):
    return 2*x

if __name__ == '__main__':
    with ProcessPoolExecutor(max_workers=2) as executor:
        xs = [1,2]
        results = executor.map(foo, xs)
        for result in results:
            print(result)

问题根源解释

当用spawn方式启动子进程时,每个子进程都会重新导入你的主脚本模块。如果你的多进程代码不在if __name__ == '__main__':块里,子进程导入模块时会重复执行创建ProcessPoolExecutor、提交任务的代码,进而无限递归创建新进程,最终触发你看到的RuntimeError。

至于错误里提到的freeze_support(),那是专门给Windows系统打包可执行文件用的,MacOS下完全不需要添加,只要保证主逻辑在if __name__ == '__main__':块内就可以解决问题。

运行修正后的代码,你会得到预期的输出:

2
4

内容的提问来源于stack exchange,提问作者saulspatz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:47:36