【发布时间】:2015-08-15 21:42:20
【问题描述】:
我希望能够使用多处理库中的值模块来跟踪数据。据我所知,当涉及到 Python 中的多处理时,每个进程都有自己的副本,所以我无法编辑全局变量。我希望能够使用 Values 来解决这个问题。有谁知道我如何将 Values 数据传递到池化函数中?
from multiprocessing import Pool, Value
import itertools
arr = [2,6,8,7,4,2,5,6,2,4,7,8,5,2,7,4,2,5,6,2,4,7,8,5,2,9,3,2,0,1,5,7,2,8,9,3,2,]
def hello(g, data):
data.value += 1
if __name__ == '__main__':
data = Value('i', 0)
func = partial(hello, data)
p = Pool(processes=1)
p.map(hello,itertools.izip(arr,itertools.repeat(data)))
print data.value
这是我得到的运行时错误:
RuntimeError: Synchronized objects should only be shared between processes through inheritance
有谁知道我做错了什么?
【问题讨论】:
-
我认为您需要将
data变量传递给所有进程。 -
@TomDalton 我刚刚使用 itertools 更新了代码以将数据变量传递给 hello 函数,我现在收到一个错误,我不确定它为什么会发生。
-
你为什么不从
hello()返回数据呢?这就是map的全部意义所在。
标签: python python-multiprocessing