python - 在 python 中使用 multiprocessing.Manager 在进程之间共享数据

标签 python multiprocessing shared-objects

以下是来自 http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes 的调整示例

from multiprocessing import Process, Manager

def f(d):
    print d                 # 1
    print type(d)

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    p = Process(target=f, args=(d))
    p.start()
    p.join()

我正在尝试做类似的事情

from multiprocessing import Process, Manager
class abcd(Process):

    def __init__(self,d):
        Process.__init__(self)
        self.d = d
        print self.d            # 2
        print type(self.d)

    def run(self):
        print self.d            # 3
        print type(self.d)

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()

    proc = abcd(d)
    proc.start()

真正让我困扰的是,在标记为 1 和 2 的行中,我得到了我所期望的 {} - 空白字典。但在第 3 行它打印了

<DictProxy object, typeid 'dict' at 0x18ac9d0; '__str__()' failed>

从 Process 继承时我错过了什么吗?

最佳答案

问题是,您的主进程 fork 进程有机会从字典中获取值之前终止。

您应该调用 proc.join() 让进程有机会获取字典。

如果您查看示例代码,您会看到完全相同的内容。

关于python - 在 python 中使用 multiprocessing.Manager 在进程之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11432952/

相关文章:

python - 向后移植 Python 3. 4's regular expression "fullmatch()"到 Python 2

python - Django Choice 领域 Web 服务最佳实践

python - PIL/Pillow 将图像转换为列表并再次返回

ios - 更新后删除了 Air iOS SharedObject

Linux g++ : linking with static libstdc++ without exporting it

python:如何通过ssh远程运行脚本

python - 无法立即停止\杀死 multiprocessing.Pool 产生的所有进程

python - 在 Pandas 中使用多处理读取 csv 文件的最简单方法

Python 在线程中调用 pipe.communicate()

linux - 如何处理不匹配的共享对象的 "undefined symbol"错误