我試圖在一個進程中設置一個全局變量,並從另一個進程讀取它。 這基本上是我在做什麼:從不同的函數調用時,全局變量有不同的值
from multiprocessing import Process
import time
rocket = 0
def func1():
global rocket
while rocket < 10:
rocket += 1
print("Func1: " + str(rocket))
time.sleep(5)
def func2():
while rocket < 10:
print ("Func2: " + str(rocket))
time.sleep(1)
if __name__=='__main__':
p1 = Process(target = func1)
p1.start()
p2 = Process(target = func2)
p2.start()
我覺得這個代碼應該做的事情:
- FUNC1 1每五秒鐘
- 每一秒FUNC2提高了全局變量「火箭」讀取全局變量火箭並打印
- 這兩種方法運行parralel直到「火箭」 == 10
所以期望輸出應該是這樣的:
Func1: 1
Func2: 1
Func2: 1
Func2: 1
Func2: 1
Func2: 1
Func1: 2
Func2: 2
Func2: 2
#... and so on
但實際產量是這樣:
Func1: 1
Func2: 0
Func2: 0
Func2: 0
Func2: 0
Func2: 0
Func1: 2
Func2: 0
Func2: 0
#... and so on
當從FUNC2 '火箭' 印刷始終保持0
我聲明'火箭'作爲func1的全局變量as you should
我在這裏失蹤了什麼?
的可能的複製[Python的多處理全局變量的更新不會返回到父(HTTPS: //stackoverflow.com/questions/11055303/python-multiprocessing-global-variable-updates-not-returned-to-parent) –