4
我運行一個簡單的多進程程序(下面的代碼)。我只做2個處理器,然後初始化一個隊列來存儲結果。來自multiprocessing中multiprocessing.Queue()的返回值Python
我想知道爲什麼用同名q
,但每次打印出不同的值。 我知道隊列存儲2返回值,從pro1
和pro2
。但我所料,這是這樣的:
q = [1,2]
或
q=[2,1] #depend on which one runs first
我無法弄清楚如何一個變量q
可以是1或2
這讓我很困惑。 謝謝。
代碼:
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())
結果:
Starting thread 2
Starting thread 1
('q is ', 1)
('another q is ', 2)
我明白了。謝謝,這真的很有道理。 – Catbuilts