Python 传递字典以在多处理中处理 [英] Python passing dictionary to process in multiprocessing
本文介绍了Python 传递字典以在多处理中处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含(大量)不同属性的类,包括一些字典.当我将类的实例传递给新进程时,所有数值似乎都被正确传递,但类对象中的所有字典都被清空.
I have a class that contains a (large) number of different properties, including a few dictionaries. When I pass an instance of the class through to a new process, all of the numeric values seem to get passed in correctly, but any dictionaries that were in the class object get emptied.
这是我编写的一个简单测试来演示我的问题:
Here's a simple test I cooked up that demonstrates my problem:
from multiprocessing import Process
class State:
a = 0
b = {}
def f(s, i):
print "f:", s.a, s.b
def main():
state = State()
state.a = 11
state.b['testing'] = 12
print "Main:", state.a, state.b
ps = []
for i in range(1):
p = Process(target=f, args=(state, i))
p.start() # Do the work
ps.append(p)
for p in ps:
p.join()
if __name__ == '__main__':
main()
我希望输出是
Main: 11 {'testing': 12}
f: 11 {'testing': 12}
但我得到了
Main: 11 {'testing': 12}
f: 11 {}
推荐答案
我最终解决了这个问题,除了状态之外,还显式地传递了字典.例如
I ended up working around this problem by passing the dictionaries in explicitly in addition to the state. e.g.
p = Process(target=f, args=(state, i, state.b))
这篇关于Python 传递字典以在多处理中处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文