title: Sharing a multiprocessing synchronization primitive across processes
body: <p>(Python 3.4, Linux).</p>
  
  <p>I have a main process 'P', which forks 8 processes ('C1' through 'C8'). I want to create <code>multiprocessing.Barrier</code> that ensures all the 8 child processes are in sync at a certain point.</p>
  
  <p>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:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>But in my case, I do not know the details required to create the <code>Barrier</code> object until after the child processes start (I don't know the argument I want to pass as its <code>action</code> parameter). Therefore, I want to create <code>Barrier</code> 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 <code>Barrier</code> objects in the child process are completely independent from each other:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>I was thinking to create <code>barrier</code> in one of the child processes and pass it to the others using <code>multiprocessing.Queue</code> (or if <code>Queue</code> doesn't accept <code>Barrier</code> objects, using <code>multiprocessing.Manager().Barrier</code>). However, even if this works, I don't know how to ensure only one process actually <code>put</code>s the (7 copies of) synchronization primitives onto the queue, while the others will only <code>get</code> 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 <code>Barrier</code> in the parent process after all.)</p>