简体   繁体   English

如何制作可以在多个进程之间共享的 Manager 列表字典?

[英]How do I make a Manager list dictionary that can be shared between multiple processes?

I want to share a list of dictionaries between multiple processes like the following:我想在多个进程之间共享一个字典列表,如下所示:

msgs = [{ 1: "A", 2: "B"}, 
        {20 : "AAA", 30 : "BBB"}, 
        {100 : "777", 200 : "888"}]

I've looked at the other posts regarding how to use Manager dicts but they don't show to to make a list of another type (dict in this case)我已经查看了有关如何使用 Manager dicts 的其他帖子,但它们没有显示制作另一种类型的列表(在本例中为 dict)

For example: how can I share a dictionary across multiple processes?例如: 如何跨多个进程共享字典?

^Unfortunately, I wasn't able to extend that to what I want. ^不幸的是,我无法将其扩展到我想要的。 Also, I am not using a pool of processes.另外,我没有使用进程池。 I have 3 separate processes that I've instantiated.我已经实例化了 3 个独立的进程。

Would anyone be able to show me an example of how to make a list of dictionaries that can be shared across processes?任何人都可以向我展示如何制作可以跨进程共享的字典列表的示例吗?

If you want to share your dictionaries within the list you have to not only create the list but also the dictionaries via Manager() .如果您想在列表中共享您的字典,您不仅要创建列表,还要通过Manager()创建字典。 For example例如

msg = manager.list()
msg.append(manager.dict({ 1: "A", 2: "B"}))

Otherwise the changes to your dictionary inside the process will not be registered.否则进程内对字典的更改将不会被注册。 You might want to look a this answer for details.您可能想查看此答案以获取详细信息。

An extended version of the linked example could look something like this链接示例的扩展版本可能看起来像这样

from multiprocessing import Process, Manager

def f(msg):
    for ele in msg:
        if 1 in ele:
            ele[1] += "hi"
        if 100 in ele:
            ele[100] += "5"

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

    msg = manager.list()
    msg.append(manager.dict({ 1: "A", 2: "B"}))
    msg.append(manager.dict({20 : "AAA", 30 : "BBB"}))
    msg.append(manager.dict({100 : "777", 200 : "888"}))

    p1 = Process(target=f, args=(msg,))
    p2 = Process(target=f, args=(msg,))
    p3 = Process(target=f, args=(msg,))

    p1.start()
    p2.start()
    p3.start()
    p1.join()
    p2.join()
    p3.join()

    for d in msg:
        print(str(d))

Resulting in the output导致 output

{1: 'Ahihihi', 2: 'B'} {1:'Ahihihi',2:'B'}

{20: 'AAA', 30: 'BBB'} {20:'AAA',30:'BBB'}

{100: '777555', 200:'888'} {100:'777555',200:'888'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM