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

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的交互式环境中:

  1. 将执行逻辑包裹在if __name__ == '__main__':块内,避免子进程重复执行初始化代码
  2. 显式设置spawn启动方式,确保与Windows的多进程机制兼容,防止因启动方式冲突导致进程异常终止

这样调整后,无需拆分代码即可在VS Code的Jupyter Notebook中直接运行官方示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:05:04