Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

python 2.7 - 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()

and am wondering if I can have a shared dictionary between that CloudProc and my current main process?

EDIT: 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.

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}

So how does Python know that dict() should be called from Managers? Is there any examples I can follow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...