Reputation: 5100
I run a simple multiprocess program (the code below). I just make 2 processors, then initial a queue to store the result.
I wonder why with the same name q
, but each time it prints out a different value.
I know the queue store 2 return values, from pro1
and pro2
. But I expected, it's something like:
q = [1,2]
or
q=[2,1] #depend on which one runs first
I can not figure out how one variable q
can be 1, or 2.
It makes me so confused. Thank you.
The 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())
The result:
Starting thread 2
Starting thread 1
('q is ', 1)
('another q is ', 2)
Upvotes: 6
Views: 7287
Reputation: 507
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.
For example in your case it looks like process 1 finishes first, and then process 2.
Thus after both processes are complete the queue will look like
[1,2]
Then when you call q.get()
you get 1
and the queue now looks like:
`[2]`
Then when you call q.get()
again you will get 2
and now the queue is empty.
Upvotes: 2