Windows10下VS Code Jupyter运行ProcessPoolExecutor报BrokenProcessPool错误如何解决?
Windows下VS Code Jupyter Notebook无需拆分代码运行ProcessPoolExecutor示例
问题背景
Python官方文档的concurrent.futures.ProcessPoolExecutor()示例代码,在Ubuntu系统的Jupyter Notebook中可正常运行,但在Windows10的VS Code Jupyter Notebook中执行时会抛出BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.错误(使用Anaconda打包的Python 3.10.10版本)。
用户已验证:
- 将代码放入独立
.py脚本并从Notebook调用可正常运行 - 使用
multiprocessing.Pool会导致Notebook单元格永久冻结 - 拆分worker函数到独立文件再导入的方式可行,但希望找到无需拆分代码、直接按官方文档风格运行的方法
无拆分代码的解决方案
在VS Code的Jupyter Notebook单元格中,对代码做如下调整即可直接运行:
import concurrent.futures import math import multiprocessing PRIMES = [ 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419] def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, sqrt_n + 1, 2): if n % i == 0: return False return True if __name__ == '__main__': # 显式设置多进程启动方式为spawn(Windows默认,但强制设置避免冲突) multiprocessing.set_start_method('spawn', force=True) with concurrent.futures.ProcessPoolExecutor() as executor: for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)): print(f'{number} is prime: {prime}')
原理说明
Windows系统的多进程默认采用spawn启动方式,子进程需要重新导入主模块并加载所需函数。在Jupyter Notebook的交互式环境中:
- 将执行逻辑包裹在
if __name__ == '__main__':块内,避免子进程重复执行初始化代码 - 显式设置
spawn启动方式,确保与Windows的多进程机制兼容,防止因启动方式冲突导致进程异常终止
这样调整后,无需拆分代码即可在VS Code的Jupyter Notebook中直接运行官方示例。
内容的提问来源于stack exchange,提问作者user6376297
相关产品推荐
相关产品推荐

