In short, say 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’d expect the output to be:
Init
Running
1
Instead it is
Init
Running
None
Can someone explain to me why this is the case? What am I not understanding, and how should I go about doing it correctly?
Thanks.
The moment you say
p.start(), a separate process is forked off of the main process. All variable values are copied. So the main process has one copy ofp, and the forked process has a separate copy ofp. TheWorkermodifies the forked process’s copy ofp.value, but the main process’sp.valuestill isNone.There are many ways to share objects between processes. In this case, perhaps the easiest way is to use a mp.Value:
Note that the
mp.Valuehas a default value of0.0. It can not be set toNone.