python - 为什么 dict 没有在 python 多处理中更新?

标签 python python-2.7 multiprocessing

请检查下面的代码。

我初始化了一个字典并将其发送给函数 f。我检查了 return_dict 的地址。它在过程内部没有变化。所以我认为字典应该更新

但是没有更新,这是为什么呢?

from multiprocessing import Process

return_dict = dict({})
print id(return_dict)


def f(value, return_dict):
    return_dict['value'] = value
    print return_dict


p = Process(target=f, args=(100, return_dict))
p.start()
p.join()
print return_dict

最佳答案

您的 Process() 创建了另一个进程。当子进程产生时,它从父进程继承对象,但是对这些对象的修改只会修改子进程内存中的对象,而这些更改对父进程都是不可见的。

您可以使用 Manager() 来解决这个问题:

from multiprocessing import Process, Manager

def f(value, return_dict):
    return_dict['value'] = value
    print return_dict

d = Manager().dict()    
p = Process(target=f, args=(100, d))
p.start()
p.join()
print d

关于python - 为什么 dict 没有在 python 多处理中更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47332937/

相关文章:

python - 从列表条目中连接 python 字符串

python-2.7 - 在第一次出现值之前删除所有行

python - 如何在 python 中编写多进程 Web 服务器

python - 与 Python 代码相比,我如何提高 Rust 代码的性能?

python - 如何在 Windows 上安装 matplotlib 2.0 beta?

python - 两个文件的 python 'open' 中的模拟

python - 如何在 pygame 中水平翻转图像?

python - Django 未处理的异常

python - 如何使用多处理在Python中运行多个异步进程?

python - 多处理、终止和损坏队列