Return value from multiprocessing.Queue() in multiprocessing Python
<p>I run a simple multiprocess program (the code below). I just make 2 processors, then initial a queue to store the result.</p>

<p>I wonder why with the same name <code>q</code>, but each time it prints out a different value.
I know the queue store 2 return values, from <code>pro1</code> and <code>pro2</code>. But I expected, it's something like: </p>

<pre><code>q = [1,2]
</code></pre>

<p>or</p>

<pre><code>q=[2,1] #depend on which one runs first
</code></pre>

<p>I can not figure out how one variable <code>q</code> can be 1, or 2.</p>

<p>It makes me so confused. 
Thank you.</p>

<p><strong>The code:</strong></p>

<pre><code>import multiprocessing


def run(ID, q):
    print("Starting thread %s " % (ID))

    q.put(ID)
    return None

if __name__ == '__main__':
    q = multiprocessing.Queue()  #store the result
    pro1 = multiprocessing.Process(target=run, args=(1,q))
    pro2 = multiprocessing.Process(target=run, args=(2,q))

    pro1.start()
    pro2.start()

    pro1.join()
    pro2.join()

    print("q is ", q.get())
    print("another q is ", q.get())
</code></pre>

<p><em>The result</em>:</p>

<pre><code>Starting thread 2 
Starting thread 1 
('q is ', 1)
('another q is ', 2)
</code></pre>

<p>I'm not 100% sure what you're confused about exactly, but here's what I think will help, but please correct me if I'm off track. Your queue has the outputs of both processes on it. You're just getting the one that finished first.</p>

<p>For example in your case it looks like process 1 finishes first, and then process 2.</p>

<p>Thus after both processes are complete the queue will look like</p>

<pre><code>[1,2]
</code></pre>

<p>Then when you call <code>q.get()</code> you get <code>1</code> and the queue now looks like:</p>

<pre><code>`[2]`
</code></pre>

<p>Then when you call <code>q.get()</code> again you will get <code>2</code> and now the queue is empty.</p>

python multiprocessing