在进程之间共享字典 [英] share dict between processes
问题描述
我创建了一个单独的进程来处理我的云服务.我是这样生成的:
I spawn a seperate process to handle my cloud services. I spawnb it like this:
CldProc = Process(target=CloudRun)
CldProc.start()
我想知道我是否可以在该 CloudProc 和我当前的主进程之间拥有一个共享字典?
and am wondering if I can have a shared dictionary between that CloudProc and my current main process?
或者,我正在考虑使用 pickle 将我的数据从进程中转储到文件中并重新加载,这需要我使用 join() 来等待进程完成并退出.
Alternatively I am thinking to use pickle to dump my data into a file from the process and load it back, this requires me to use join() to wait for the process to complete and exit.
第二次编辑因此,我现在将我的 dict 声明为 mac_dict={} ,然后将其填充到我的子进程中并希望在我的主进程中访问它.现在我刚刚尝试了这个:
2nd EDIT So, I now have my dict declared like mac_dict={} and then I fill it in my subprocess and want to access it in my main process. Now I just tried this:
>>> dict = dict()
>>> dict['A'] = 1
>>> print dict
{'A': 1}
那么 Python 是如何知道应该从 Managers 调用 dict() 的呢?有什么可以借鉴的例子吗?
So how does Python know that dict() should be called from Managers? Is there any examples I can follow?
推荐答案
明白了,为了简化,我是这样处理的:
Got it, to simplify, I did it like this:
from multiprocessing import Process, Manager
def myf(myd):
myd[1] = "HELLO WORLD!"
def proc(d):
myf(d)
m=Manager()
locdict=m.dict()
locdict[2] = "HI BUDDY!"
p = Process(target=proc, args=(locdict,))
p.start()
p.join()
print locdict
这篇关于在进程之间共享字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!