如何在第一个子进程完成时终止所有子进程

How to terminate all subprocesses when the first one completes

如何同时终止两个进程?下面的代码启动并等待两个进程结束执行,直到它终止它们,我想在其中一个进程首先达到目标时终止这两个进程。 (进入循环1000次并计算i^i)

from multiprocessing import Process
from os import _exit

def foo():
    for i in range(1000):
        i ** i
    print('EXITED')
    _exit(0)
    # exit(0)
    # quit()
    # __import__('sys').exit(0)

if __name__ == '__main__':
    p1 = Process(target=foo, daemon=True)
    p2 = Process(target=foo, daemon=True)
    for process in (p1, p2):
        process.start()

    for process in (p1, p2):
        process.join()

向每个进程传递一个 multiprocessing.Event 进程在完成时设置的实例。主进程只是等待设置事件以指示进程已完成。

如果任务是守护进程并且主进程没有进一步的事情要做,它可以简单地退出,任何 运行 的守护进程都将自动终止。否则,主进程可以显式终止所有进程,在这种情况下,无需使子进程成为守护进程。

def foo(event, n):
    for i in range(n):
        i ** i
    print('EXITED, n =', n)
    event.set()

if __name__ == '__main__':
    from multiprocessing import Process, Event

    event = Event()
    # So processes end at different times:
    p1 = Process(target=foo, daemon=True, args=(event, 1_000_000_000))
    p2 = Process(target=foo, daemon=True, args=(event, 1_000))
    for process in (p1, p2):
        process.start()

    # Wait for a process to complete:
    event.wait()
    # exiting is sufficient

    """
    # If you have other processing to do, then explicitly terminate the subprocesses,
    # in which case there was no need to make them daemon processes.
    for process in (p1, p2):
        process.terminate()
    """

打印:

EXITED, n = 1000