2

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.

Daniele P.
  • 98
  • 1
  • 8
  • Does this answer your question? [How can I share a class between processes?](https://stackoverflow.com/questions/28612412/how-can-i-share-a-class-between-processes) – Mohammad Moallemi Feb 23 '21 at 13:43

1 Answers1

0

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

Daniele P.
  • 98
  • 1
  • 8