如何跨多个进程共享字典? [英] how can I share a dictionary across multiple processes?

查看:80
本文介绍了如何跨多个进程共享字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以跨多个进程共享字典的内容.我一直在查看 http://docs.python.org /2/library/multiprocessing.html#shared-ctypes-objects ,但它仅描述了如何共享变量,但我还没有弄清楚如何共享完整的字典. 我知道,我可以使用pickle通过将其存储到文件中来共享它,但这似乎不是很有效.原因是我在具有闪存的系统上运行此程序?有什么提示吗?

I was wondering if it's possible to share the contents of a dictionary across multiple processes. I've been looking at http://docs.python.org/2/library/multiprocessing.html#shared-ctypes-objects but it only describes how to share variables but I haven't figured out how I can share a complete dictionary. I know, I could use pickle to share it via storing it to a file but that seems to not be very efficient esp. cause I'm running this on a system with flash memory... any tips?

谢谢, 罗恩

推荐答案

使用multiprocessing库中的manager.

from multiprocessing import Process, Manager

def f(d):
    for i in range(10000):
        d['blah'] += 1

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    d['blah'] = 0
    procs = [ Process(target=f, args=(d,)) for _ in range(10) ]
    for p in procs:
        p.start()
    for p in procs:
        p.join()

    print d

这篇关于如何跨多个进程共享字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆