Share object between processes in python

拜拜、爱过 提交于 2019-12-14 02:07:53

问题


I am looking for a dead simple example on how to share a complex object between two or more processes in python. On my main i have something like

if __name__ == "__main__":
    FirstClass().start()
    SecondClass().start()

etc... and each class is defined like:

class FirstClass(multiprocessing.Process):
    def __init__(self):
        super(FirstClass, self).__init__()
[...]

I would like to have a MySharedClass with inside all the data i need (list of custom objects and so on) that i can access and modify from subprocesses... others subprocesses should see the updated data ofcourse.

I understand i should use a Manager but documentation looks a bit confusing for my skills. Thanks in advance.


回答1:


Just found a solution... main:

from multiprocessing.managers import BaseManager

class ShareManager(BaseManager):
pass


ShareManager.register('SharedData', SharedData)

if __name__ == "__main__":
    manager = ShareManager()
    manager.start()
    shared = manager.SharedData()
    FirstClass(shared).start()

where SharedData is my shared class... and this is the sub class:

class FirstClass(multiprocessing.Process):

    def __init__(self, shared):
        super(FirstClass, self).__init__()
        self.shared = shared

PS. make sure the main thread don't die or you will lose the manager



来源:https://stackoverflow.com/questions/47877508/share-object-between-processes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!