python3 多处理 map_async 不是 运行 所有任务

python3 multiprocessing map_async not running all tasks

我的代码如下所示:

import multiprocessing as mp

def myfunc(args):
    val1, val2 = args
    print("now running", val1, val2, "node=", mp.current_process().name)
    do_stuff()
    return (args, output)

args = [(1,2), (2,3), (4,5), ...] # 27654 args

pool = mp.Pool(processes = 16)

gen_output = pool.map_async(myfunc, args)

for output in gen_output.get(): 
    args_copy, output_i = output
    

我的初始列表 (args) 有 27,654 个元组,但在计算打印输出(“now 运行ning”)后,我只得到 14,671 个。此外,我无法轻松检查,但似乎我也没有得到未打印出来的 args 的输出。
除了执行 运行 的 args 的打印输出之外,没有错误消息或警告。 \

我怀疑一些 child 节点根本没有 运行。有谁知道可能导致这种情况的原因以及如何解决?
打印语句应该告诉我 运行ning 在每个 child 节点上哪个任务。但通常它只打印 6 或 7 个不同的 children "ForkPoolWorker" 1,5,6,9,12,16 例如。 \ 我正在使用 SLURM 集群 运行 这个脚本并请求 16 个节点。

>>> cat job.sh
/bin/bash
#SBATCH -o tmp.out
#SBATCH -e tmp.err
#SBATCH -n 16 
#SBATCH -p my_partition
#SBATCH --mem=16g

python3 my_script.py. -n 16 

参数 n 将转到 pool = mp.Pool(processes = options.n)

您是否尝试过使用 concurrent.futures.ProcessPoolExecutor() 作为更通用的方法?

import concurrent.futures

def myfunc(args):
    val1, val2 = args
    print("now running", val1, val2)
    do_stuff()
    return (args, output)

args = [(1,2), (2,3), (4,5), ...] # 27654 args
with concurrent.futures.ProcessPoolExecutor(max_workers=16) as executor:
    for args_copy, output in executor.map(myfunc, args):
        ...

I am using a SLURM cluster to run this script and request 16 nodes.

您的代码显然对 SLURM 一无所知,并且每个节点 启动 16 个进程。这是你想要做的吗?

我要回答我自己的问题。我发现另一个问题 Child processes created with python multiprocessing module won't print 似乎与我自己的问题相同。
我刚刚在打印语句后添加了 sys.stdout.flush()sys.stderr.flush(),我得到了正确的计数。
此外,丢失的输出是另一个不相关的错误。我仔细检查了一下,即使 pintout 与预期计数不匹配,该函数仍然 returns 正确的输出数量。