Python class inheriting multiprocessing, problems with access to class members

In short, I have the following:

import multiprocessing class Worker(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) print "Init" self.value = None def run(self): print "Running" self.value = 1 p = Worker() p.start() p.join() print p.value 

I expect the output to be:

 Init Running 1 

Instead of this

 Init Running None 

Can someone explain to me why this is so? What I don’t understand, and how should I do it right?

Thanks.

+6
python multiprocessing
source share
1 answer

The moment you say p.start() , a separate process is interrupted from the main process. All variable values ​​are copied. Thus, the main process has one copy of p , and the forked process has a separate copy of p . Worker modifies a copy of the forked p.value process, but the main p.value process is still None .

There are many ways to exchange objects between processes. In this case, perhaps the easiest way is to use mp.Value :

 import multiprocessing as mp class Worker(mp.Process): def __init__(self): print "Init" mp.Process.__init__(self) self.num = mp.Value('d', 0.0) def run(self): print "Running" self.num.value = 1 p = Worker() p.start() p.join() print p.num.value 

Note that mp.Value has a default value of 0.0 . It cannot be set to None .

+9
source share

All Articles