Voglio eseguire una serie di lavori in parallelo e quindi continuare una volta che tutti i lavori sono terminati. Ho qualcosa di simileAttendi che tutti i processi di multiprocesso finiscano prima di continuare
# 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 ***')
funziona, ma sono sicuro che ci deve essere un modo migliore per aspettare che tutti i lavori per finire di iterazione di nuovo e di nuovo fino a quando hanno finito.
Questo è esattamente quello che stavo cercando, grazie :) – Hybrid
Nota per i futuri utenti: questo utilizzo può essere indicativo di un'attività che potrebbe beneficiare di un [Pool] (https://docs.python.org/2/library /multiprocessing.html#using-a-pool-of-workers). – kungphu