问题
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