Anuvrat Parashar
Anuvrat Parashar

Reputation: 3100

Sharing data amongst processes using multiprocessing.Manager in python

Following is a tweaked example from http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes

from multiprocessing import Process, Manager

def f(d):
    print d                 # 1
    print type(d)

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

    d = manager.dict()
    p = Process(target=f, args=(d))
    p.start()
    p.join()

I am trying to do something like

from multiprocessing import Process, Manager
class abcd(Process):

    def __init__(self,d):
        Process.__init__(self)
        self.d = d
        print self.d            # 2
        print type(self.d)

    def run(self):
        print self.d            # 3
        print type(self.d)

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

    d = manager.dict()

    proc = abcd(d)
    proc.start()

What is actually troubling me is that at lines marked 1 and 2 I get what I expect a {} - blank dictionary. But at line 3 it prints

<DictProxy object, typeid 'dict' at 0x18ac9d0; '__str__()' failed>

Did I miss something while inheriting from Process?

Upvotes: 2

Views: 1910

Answers (1)

isset
isset

Reputation: 2203

the problem is that, your main process is terminating before the forked process has a chance to grab the value from the dict.

You should call proc.join() to give the process a chance to grab the dict.

If you look in the example code then you will see the exact same thing.

Upvotes: 4

Related Questions