我希望并行运行一堆作业,然后在所有作业完成后继续。我有类似的东西
# 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 ***')
它确实有效,但我确信必须有一个更好的方法来等待所有工作完成,而不是一遍又一遍地迭代它们直到它们完成。
你可以使用join。它让你等待另一个进程结束。
t1 = Process(target=f, args=(x,))
t2 = Process(target=f, args=('bob',))
t1.start()
t2.start()
t1.join()
t2.join()
您也可以使用barrier它适用于线程,让您指定一些您想要等待的进程,一旦达到此数量,就可以将它们屏障。这里客户端和服务器被假设为Process。
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。