I am running a simple multiprocessor program (code below). I just make 2 processors and then initialize the queue to store the result.
I wonder why with the same name q, but each time it prints a different value. I know that return values in queue storage 2 are from pro1and pro2. But I was expecting something like:
q = [1,2]
or
q=[2,1] #depend on which one runs first
I can not understand how one variable qcan be 1 or 2.
It bothers me so much. Thank.
The code:
import multiprocessing
def run(ID, q):
print("Starting thread %s " % (ID))
q.put(ID)
return None
if __name__ == '__main__':
q = multiprocessing.Queue()
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())
Result:
Starting thread 2
Starting thread 1
('q is ', 1)
('another q is ', 2)
source
share