等待所有多处理作业完成后再继续

Hyb*_*rid 27 python parallel-processing multiprocessing

我希望并行运行一堆作业,然后在所有作业完成后继续.我有类似的东西

# 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 ***')
Run Code Online (Sandbox Code Playgroud)

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

jay*_*ant 36

关于什么?

for job in jobs:
    job.join()
Run Code Online (Sandbox Code Playgroud)

这将阻塞,直到第一个进程完成,然后是下一个进程,依此类推.了解更多join()

  • 未来搜索者的注意事项:此用法可以指示可以从[池](https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers)中受益的任务. (4认同)
  • 如果“job”已经完成并且我们对该对象调用“join()”方法,会发生什么? (2认同)

Rbt*_*tnk 5

您可以使用join。它让您等待另一个过程结束。

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

t1.start()
t2.start()

t1.join()
t2.join()
Run Code Online (Sandbox Code Playgroud)

您也可以使用barrier它与线程一样工作,允许您指定要等待的进程数,一旦达到此数目,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)
Run Code Online (Sandbox Code Playgroud)

而且,如果您想要共享数据和更多流控制等更多功能,则可以使用管理器