Python:无法访问通过多处理更改的内存

标签 python python-2.7 multiprocessing python-multiprocessing

这是 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.Queuemutiprocess.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/

相关文章:

Python 多处理 : AttributeError: 'Test' object has no attribute 'get_type'

python - Matplotlib hexbin : How to avoid displaying bins where np. 平均值为零

python - 你能覆盖一个由函数结果定义的变量而不先在 python 中清除吗?

python - 获取文本小部件的长度

php - 如何设计一个基于正在运行的脚本后端的 AJAX 界面来显示进度条

python - 在 python 中使用多处理并行化递归代码

python - 空间复杂度是多少?

python - 格式化python字符串中的换行符

python - 根据 Django 模型中的条件根据需要创建模型字段

python - 不支持 pandas dataframe 到 mysql db 错误数据库风格 mysql