在继续之前等待所有多处理作业完成

Wait for all multiprocessing jobs to finish before continuing

我想运行并行处理一堆作业,然后在所有作业完成后继续。我有类似

的东西
# based on example code from https://pymotw.com/2/multiprocessing/basics.html
import multiprocessing
import random
import time

def worker(num):
    """A job that runs for a random amount of time between 5 and 10 seconds."""
    time.sleep(random.randrange(5,11))
    print('Worker:' + str(num) + ' finished')
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    # Iterate through the list of jobs and remove one that are finished, checking every second.
    while len(jobs) > 0:
        jobs = [job for job in jobs if job.is_alive()]
        time.sleep(1)

    print('*** All jobs finished ***')

它有效,但我确信必须有更好的方法来等待所有作业完成,而不是一次又一次地迭代它们直到它们完成。

怎么样?

for job in jobs:
    job.join()

这会阻塞直到第一个进程完成,然后是下一个进程,依此类推。查看更多关于 join()

你可以利用join。 它让你等待另一个进程结束。

t1 = Process(target=f, args=(x,))
t2 = Process(target=f, args=('bob',))

t1.start()
t2.start()

t1.join()
t2.join()

您也可以使用 barrier 它与线程一样工作,让您指定要等待的进程数量,一旦达到该数量,就释放它们。这里假定客户端和服务器作为进程产生。

b = Barrier(2, timeout=5)

def server():
    start_server()
    b.wait()
    while True:
        connection = accept_connection()
        process_server_connection(connection)

def client():
    b.wait()
    while True:
        connection = make_connection()
        process_client_connection(connection)

如果您想要共享数据和更多流量控制等更多功能,您可以使用 manager