Answer a question

I want to run a bunch of jobs in parallel and then continue once all the jobs are finished. I've got something like

# 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 ***')

it works, but I'm sure there must be a better way to wait for all the jobs to finish than iterating over them again and again until they are done.

Answers

What about?

for job in jobs:
    job.join()

This blocks until the first process finishes, then the next one and so on. See more about join()

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐