Python 中的多线程/处理
您好,我正在尝试使用多处理并行定义字典的值。当函数 f() 在“池”外部调用时,字典值被正确设置。但是在池中调用失败了。
我做错了什么?谢谢。
from multiprocessing import Pool
hits={}
def f(x):
hits[x] = x #this will involve a complex operation
f('000')
print hits['000']
if __name__ == '__main__':
pool = Pool(processes=2)
inputs = ['a','b','c']
result = pool.map(f, inputs)
print hits['a']
Hello I am trying define values of a dictionary in parallel using multiprocessing. When the function f() is called outside "pool" the dictionary value is set correctly. In the pool call however it fails.
What am I doing wrong? Thanks.
from multiprocessing import Pool
hits={}
def f(x):
hits[x] = x #this will involve a complex operation
f('000')
print hits['000']
if __name__ == '__main__':
pool = Pool(processes=2)
inputs = ['a','b','c']
result = pool.map(f, inputs)
print hits['a']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您生成了一堆继承
hits
当前值的子进程。每个子进程都会获取自己的hits
副本并对其进行修改,然后退出,删除hits
的进程本地副本。multiprocessing.Pool.map()
的预期用途是使用它的返回值,您将忽略该值。每个进程都可以返回其命中
的副本,并且您最终加入这些副本。You spawn a bunch of subprocesses which inherit the current value of
hits
. Each subprocess get its own copy ofhits
and modifies it, then exits, dropping the process-local copy ofhits
.The intended use of
multiprocessing.Pool.map()
is to use its return value, which you are ignoring. Each process could return its copy ofhits
, and you finally join these copies.