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

Python中ProcessPoolExecutor进程数与top显示不符的原因咨询

为什么ProcessPoolExecutor设置max_workers=3却出现4个进程?

我在使用concurrent.futures.ProcessPoolExecutor时,设置max_workers=3,但通过top命令观察到有4个进程实例,多次测试都是max_workers+1的情况,想知道这个现象的原因。

测试代码

import concurrent.futures
import math
import time

PRIMES_CHUNKG_A = [
    112272535095293,
    112582705942171,
    112272535095293
]

PRIMES_CHUNKG_B = [
    115280095190773,
    115797848077099,
    1099726899285419
]

PRIME_CHUMKS = [PRIMES_CHUNKG_A, PRIMES_CHUNKG_B]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    time.sleep(60)  # this is only for test purposses

    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

def main_tp_chumks(prime_chumk):
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for number, prime in zip(prime_chumk, executor.map(is_prime, prime_chumk)):
            print('%d is prime: %s' % (number, prime))

def cmbine_pp_tp():
    with concurrent.futures.ProcessPoolExecutor(max_workers=3) as executor_pp:
        executor_pp.map(main_tp_chumks, PRIME_CHUMKS)


if __name__ == '__main__':
    start_time = time.time()
    cmbine_pp_tp()
    stop_time = time.time()
    print(f"Elapsed time - combined process/thread pool: {stop_time-start_time}")

原因说明

  • 多出来的进程是主进程,也就是你运行脚本本身的进程,它不属于max_workers指定的工作进程范围。
  • ProcessPoolExecutor的max_workers参数定义的是后台工作进程的数量,主进程会负责管理这些工作进程:包括任务调度、结果收集、进程生命周期管控等,它本身会一直存在直到所有工作进程完成任务。
  • 你的场景里,主进程启动了3个工作进程处理任务,加上主进程自己,总共就是4个进程,这是ProcessPoolExecutor的正常工作机制。
  • 可以通过打印进程ID验证:在脚本开头导入os模块,添加print(f"主进程PID: {os.getpid()}"),再在main_tp_chumks函数内添加print(f"工作进程PID: {os.getpid()}"),运行后就能看到主进程和3个不同PID的工作进程,总数正好是4个。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:57:50