問題描述
可能重復:
Python 多處理全局變量更新未返回給父級
我正在使用具有多個內核的計算機,為了提高性能,我真的應該使用多個內核.但是,我很困惑為什么這些代碼沒有達到我的預期:
I am using a computer with many cores and for performance benefits I should really use more than one. However, I'm confused why these bits of code don't do what I expect:
from multiprocessing import Process
var = range(5)
def test_func(i):
global var
var[i] += 1
if __name__ == '__main__':
jobs = []
for i in xrange(5):
p = Process(target=test_func,args=(i,))
jobs.append(p)
p.start()
print var
還有
from multiprocessing import Pool
var = range(5)
def test_func(i):
global var
var[i] += 1
if __name__ == '__main__':
p = Pool()
for i in xrange(5):
p.apply_async(test_func,[i])
print var
我希望結果是 [1, 2, 3, 4, 5]
但結果是 [0, 1, 2, 3, 4]
.
I expect the result to be [1, 2, 3, 4, 5]
but the result is [0, 1, 2, 3, 4]
.
在將全局變量與進程一起使用時,我肯定遺漏了一些微妙之處.這甚至是要走的路還是我應該避免嘗試以這種方式更改變量?
There must be some subtlety I'm missing in using global variables with processes. Is this even the way to go or should I avoid trying to change a variable in this manner?
推薦答案
如果您正在運行兩個單獨的進程,那么它們將不會共享相同的全局變量.如果要在進程之間傳遞數據,請查看使用 send 和 recv.看看 http://docs.python.org/library/multiprocessing.html#shared-state-between-processes 舉一個與您正在做的類似的例子.
If you are running two separate processes, then they won't be sharing the same globals. If you want to pass the data between the processes, look at using send and recv. Take a look at http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes for an example similar to what you're doing.
這篇關于全局變量和 Python 多處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!