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

pool.map_async()回调函数无法正常工作,求问题排查指导

问题原因与解决方案

你的代码里pool.map_async是异步执行的,主进程提交任务后立刻走到打印耗时的步骤,随后直接退出——此时子进程还没完成任务,回调函数prt根本没机会被调用。

解决办法

你需要让主进程等待异步任务完成,有两种常用方式:

方式1:调用result.wait()

直接等待map_async返回的AsyncResult对象完成:

import os
import multiprocessing
import time

def cube(x):
    return "{}^3={}".format(x, x**3)
def prt(value):
    print(value)

if __name__ == "__main__":
    pool = multiprocessing.Pool(3)
    start_time = time.perf_counter()
    result = pool.map_async(cube, range(1,1000), callback=prt)
    result.wait()  # 等待异步任务执行完毕,确保回调被触发
    finish_time = time.perf_counter()
    print(f"Program finished in {finish_time-start_time} seconds")

方式2:调用pool.close() + pool.join()

先关闭进程池禁止新任务提交,再等待所有子进程结束:

import os
import multiprocessing
import time

def cube(x):
    return "{}^3={}".format(x, x**3)
def prt(value):
    print(value)

if __name__ == "__main__":
    pool = multiprocessing.Pool(3)
    start_time = time.perf_counter()
    result = pool.map_async(cube, range(1,1000), callback=prt)
    pool.close()  # 关闭进程池,不再接受新任务
    pool.join()   # 等待所有子进程完成任务
    finish_time = time.perf_counter()
    print(f"Program finished in {finish_time-start_time} seconds")

补充说明

map_async是非阻塞方法,提交任务后主进程不会自动等待子进程完成。回调函数的执行依赖主进程的存活,一旦主进程提前退出,所有子进程会被强制终止,回调也就无法执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:30:57