問(wèn)題描述
可能重復(fù):
Python 多處理全局變量更新未返回給父級(jí)
我正在使用具有多個(gè)內(nèi)核的計(jì)算機(jī),為了提高性能,我真的應(yīng)該使用多個(gè)內(nèi)核.但是,我很困惑為什么這些代碼沒(méi)有達(dá)到我的預(yù)期:
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:
還有
我希望結(jié)果是 [1, 2, 3, 4, 5]
但結(jié)果是 [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]
.
在將全局變量與進(jìn)程一起使用時(shí),我肯定遺漏了一些微妙之處.這甚至是要走的路還是我應(yīng)該避免嘗試以這種方式更改變量?
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?
推薦答案
如果您正在運(yùn)行兩個(gè)單獨(dú)的進(jìn)程,那么它們將不會(huì)共享相同的全局變量.如果要在進(jìn)程之間傳遞數(shù)據(jù),請(qǐng)查看使用 send 和 recv.看看 http://docs.python.org/library/multiprocessing.html#shared-state-between-processes 舉一個(gè)與您正在做的類(lèi)似的例子.
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.
這篇關(guān)于全局變量和 Python 多處理的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!