(Python 3.4, Linux).
I have a main process 'P', which forks 8 processes ('C1' through 'C8'). I want to create multiprocessing.Barrier
that ensures all the 8 child processes are in sync at a certain point.
Everything works fine if I define the synchronization primitive in the parent process, so that when I fork the child processes it is properly inherited:
import multiprocessing as mp
barrier = mp.Barrier(8)
def f():
# do something
barrier.wait()
# do more stuff
def main():
for i in range(8):
p = mp.Process(target = f)
p.start()
if __name__ == '__main__':
main()
But in my case, I do not know the details required to create the Barrier
object until after the child processes start (I don't know the argument I want to pass as its action
parameter). Therefore, I want to create Barrier
in one of the child processes but I don't know how to make it available to the other child processes. The following won't work of course because the 8 Barrier
objects in the child process are completely independent from each other:
import multiprocessing as mp
def f():
global barrier
# do something
barrier = mp.Barrier(8)
barrier.wait()
# do more stuff
def main():
for i in range(8):
p = mp.Process(target = f)
p.start()
if __name__ == '__main__':
main()
I was thinking to create barrier
in one of the child processes and pass it to the others using multiprocessing.Queue
(or if Queue
doesn't accept Barrier
objects, using multiprocessing.Manager().Barrier
). However, even if this works, I don't know how to ensure only one process actually put
s the (7 copies of) synchronization primitives onto the queue, while the others will only get
them. (Of course, I can create a yet another synchronization primitive in the parent process just to do that, but then I might as well refactor my code to create the original Barrier
in the parent process after all.)