我正在使用 python3.6 并尝试执行类似于以下代码的内容。但是,执行后变量 mydict
仍然是 {}
我已经尝试过使用 global mydict
和不使用该方法。我认为默认情况下字典是全局的,但似乎都不起作用。
mydict = {}
def TEST(hello, integer):
global mydict
mydict[integer] = hello
print(integer)
with closing(Pool(processes=4)) as pool:
pool.starmap(TEST, [['Hello World', i] for i in range(200)])
是否可以让多个进程写入Python中的同一个字典?
最佳答案
Is is possible to have multiple processes write to the same dictionary in python?
不,不可能在进程之间共享字典,因为每个进程都在单独的内存空间中运行,其中涉及的 Python 代码由解释器的不同副本进行解释 - 尽管这可以通过共享内存来完成其他一些数据 -类型。
但是,可以使用 multiprocessing.Manager()
来模拟它协调对某些类型的共享对象的更新 - 支持的类型之一是 dict
。
这在 Sharing state between processes 中进行了讨论在线文档的部分。使用 Manager
会产生大量开销,因为它们作为单独的服务器进程与您的代码创建的任何其他进程并行运行。
无论如何,这是一个基于您问题中的代码的工作示例,该示例使用一个示例来管理对共享字典的并发更新。由于 TEST()
函数所做的事情是如此微不足道,因此这样做很可能比不使用多处理
要慢>,由于它会带来额外的开销,但是这样的东西可能适合计算密集程度更高的任务。
from contextlib import closing
from multiprocessing import Pool, Manager
def TEST(mydict, hello, integer):
mydict[integer] = hello
print(integer)
if __name__ == '__main__':
with Manager() as manager:
my_dict = manager.dict()
with closing(Pool(processes=4)) as pool:
pool.starmap(TEST, ((my_dict, 'Hello World', i) for i in range(200)))
关于python - 是否可以使用 Pool.map() 让多个进程写入同一个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013322/