这是 python 包中的 python 模块:
import multiprocessing as mp
class Test(object):
def __init__(self):
self.dict = dict()
def fill_dict(self):
self.dict = {'testing': 123}
print self.dict
if __name__ == "__main__":
tests = [Test() for i in xrange(3)]
jobs = [mp.Process(target=test.fill_dict, args=()) for test in tests]
for job in jobs:
job.start()
for job in jobs:
job.join()
print "RESULTS:"
for test in tests:
print test.dict
我运行该模块并得到如下结果:
C:\path\to\package>python -m package.path.to.module
{'testing': 123}
{'testing': 123}
{'testing': 123}
RESULTS:
{}
{}
{}
从打印输出来看,似乎每个 test.dict
都是由 multiprocessing
并行填充的。但是,当我尝试恢复结果时,test.dict 似乎是空的。有人可以解释为什么会发生这种情况以及我可以做什么来恢复非空 test.dict
吗?
编辑: @Valentin Lorentz、@Moinuddin Quadri、@zstewart
即使我将模块的后半部分更改为
if __name__ == "__main__":
test0 = Test()
test1 = Test()
test2 = Test()
jobs = list()
jobs.append(mp.Process(target=test0.fill_dict, args=()))
jobs.append(mp.Process(target=test1.fill_dict, args=()))
jobs.append(mp.Process(target=test2.fill_dict, args=()))
for job in jobs:
job.start()
for job in jobs:
job.join()
print "RESULTS:"
print test0.dict
print test1.dict
print test2.dict
我得到了相同的结果。每个进程都完全独立于其他进程(它们不共享内存,也不需要共享内存)。那么,当答案谈到进程之间共享内存时,这是否意味着主模块和多处理进程之间共享内存?
最佳答案
您不能使用内置类型在线程之间传输数据。您需要使用multiprocessing.Queue
或mutiprocess.Pipes
来执行该操作。查看:
Exchanging objects between processes .
您可以引用:Running multiple asynchronous function and get the returned value of each function 。它有关于如何使用 Queue()
而不是 list
的示例。
关于Python:无法访问通过多处理更改的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210970/