如何写入父母的字典?我已经给了一些要检索的孩子的网址列表,然后需要写入父母的字典:
from multiprocessing import Pool
import random
parent_dict={}
urls = ['www.yahoo.com','www.google.com','www.microsoft.com','www.apple.com','www.cisco.com']
def workit(url):
# retrieve the urls, process some stuff and then add that info to parent_dict
key = random.randrange(1,10) # pretend that this is the variable that we want in parent_dict
value = random.randrange(11,20)
parent_dict[key] = value
pool = Pool(processes = 5)
pool.map(workit,urls)
print parent_dict # returns {}}
答案 0 :(得分:1)
以下代码或多或少是你的,适用于处理传递python多处理文档中提到的manager.dict
。
from multiprocessing import Pool
from multiprocessing import Manager
import random
manager = Manager()
dproxy = manager.dict()
urls = ['www.yahoo.com','www.google.com','www.microsoft.com','www.apple.com','www.cisco.com']
def f(url):
shared_dict = dproxy[0]
key = random.randrange(1,10)
value = random.randrange(11,20)
shared_dict[key] = value
dproxy[0] = shared_dict
if __name__ == '__main__':
dproxy[0] = {}
pool = Pool(processes=5)
pool.map(f, urls)
print dproxy[0]
idle
开始运行时表现不佳。您将要使用python .py从命令行运行它。