Barrier就是使两个进程同时进行。假设一个进程在之前的任务跑的快了,遇到b.wait()的时候就会等待另一个进程。

    1. from multiprocessing import Queue, Lock, Barrier
    2. import multiprocessing as mp
    3. import time
    4. import os
    5. import torch
    6. # function1 计数并打印
    7. def pprint(r, b):
    8. b.wait()
    9. print('pid:{}, time:{}'.format(os.getpid(), time.time()))
    10. for i in range(r):
    11. print('thread %s: %d' % (os.getpid(), i))
    12. time.sleep(0.5)
    13. print('func1 运行完成')
    14. # function2 将数据放入列表
    15. def f(queue:Queue, b):
    16. b.wait()
    17. print('pid:{}, time:{}'.format(os.getpid(), time.time()))
    18. queue.put(torch.tensor([1,1,1]))
    19. print('func2 运行完成')
    20. if __name__ == '__main__':
    21. l = Lock()
    22. b = Barrier(2)
    23. q = Queue()
    24. process1 = mp.Process(target=pprint, args=(5, b))
    25. process2 = mp.Process(target=f, args=(q, b))
    26. process1.start()
    27. process2.start()
    28. process1.join()
    29. process2.join()
    1. pid:5896, time:1648986323.05494pid:1808, time:1648986323.05494
    2. thread 1808: 0
    3. func2 运行完成
    4. thread 1808: 1
    5. thread 1808: 2
    6. thread 1808: 3
    7. thread 1808: 4
    8. func1 运行完成

    进程1比进程2先开始,但是由于函数内有Barrier,需要等待进程2,所以Barrier使得两个进程同时开始。
    当然Barrier也可以放在主函数内进行调用,使得所有的线程(不包含主线程)完成任务后再由主线程统一继续的任务。