当父进程死亡时,如何终止Python的“ProcessPoolExecutor”?

Ric*_*ich 7 python concurrent.futures

concurrent.futures.ProcessPoolExecutor如果父进程因任何原因终止,是否有办法使进程终止?

一些细节:我正在ProcessPoolExecutor处理大量数据的工作中使用。有时我需要使用kill命令终止父进程,但是当我这样做时,进程会ProcessPoolExecutor继续运行,我也必须手动终止它们。我的主要工作循环如下所示:

with concurrent.futures.ProcessPoolExecutor(n_workers) as executor:
    result_list = [executor.submit(_do_work, data) for data in data_list]
    for id, future in enumerate(
            concurrent.futures.as_completed(result_list)):
        print(f'{id}: {future.result()}')
Run Code Online (Sandbox Code Playgroud)

executor如果父进程死亡,我可以在此处添加什么或做不同的事情来使子进程终止吗?

aar*_*ron 12

您可以在每个进程中启动一个线程,以便在父进程终止时终止:

def start_thread_to_terminate_when_parent_process_dies(ppid):
    pid = os.getpid()

    def f():
        while True:
            try:
                os.kill(ppid, 0)
            except OSError:
                os.kill(pid, signal.SIGTERM)
            time.sleep(1)

    thread = threading.Thread(target=f, daemon=True)
    thread.start()
Run Code Online (Sandbox Code Playgroud)

用法:传递initializerinitargsProcessPoolExecutor

with concurrent.futures.ProcessPoolExecutor(
        n_workers,
        initializer=start_thread_to_terminate_when_parent_process_dies,  # +
        initargs=(os.getpid(),),                                         # +
) as executor:
Run Code Online (Sandbox Code Playgroud)

即使父进程是SIGKILL/ kill -9'ed,这也有效。