使用concurrent.futures.ProcessPoolExecutor时如何获取当前进程信息
问题答案
存在完全对等的获取方式,你不需要找ProcessPoolExecutor专属的API,直接在worker函数里调用原来的multiprocessing.current_process()即可。concurrent.futures.ProcessPoolExecutor本质是对multiprocessing低层能力的高层封装,它拉起的worker进程就是标准的multiprocessing进程,没有做进程上下文的隔离或篡改,低层multiprocessing提供的所有进程信息查询接口,在ProcessPoolExecutor的worker里都能正常生效。
验证示例
import multiprocessing from concurrent.futures import ProcessPoolExecutor def demo_worker(task_id): # 直接调用multiprocessing的current_process获取当前进程信息 current_proc = multiprocessing.current_process() print(f"任务{task_id}运行进程:名称={current_proc.name}, PID={current_proc.pid}") return current_proc.pid if __name__ == "__main__": # 启动2个工作进程的进程池 with ProcessPoolExecutor(max_workers=2) as executor: pid_records = list(executor.map(demo_worker, range(4))) print("所有任务返回的进程PID:", pid_records)
运行上述代码你会发现,4个任务会被调度到2个固定的worker进程上执行,拿到的进程名、PID和系统层面记录的进程信息完全一致,和直接用低层multiprocessing启动进程拿到的结果没有任何区别。
如果你只需要简单区分进程,也可以直接用os.getpid()获取当前进程ID,效果和current_process().pid完全等价。
注意:请在被executor调度执行的worker函数内部调用进程查询接口,不要在模块顶层、worker函数外部调用这类接口。多进程启动时子进程会重新导入主模块,顶层代码执行时拿到的是导入阶段的上下文,无法获取正确的worker进程信息。
内容的提问来源于stack exchange,提问作者buhtz
相关产品推荐
相关产品推荐

