I have a python app using the multiprocessing
library and I'm running into an issue where I expect different processes to create a different instance of a class, however, they are actually creating the same instance of the class. Take this example:
from multiprocessing import Process
from time import sleep
class Foo:
name = None
def get_foobar():
return Foo()
class MyProcess(Process):
def run(self):
print('process {} running in pid {}'.format(self.name, self.pid))
my_foo = get_foobar()
print('got foo {}'.format(id(my_foo)))
if my_foo.name is None:
my_foo.name = self.name.upper()
print("foo's name is {}".format(my_foo.name))
# do some work
sleep(3)
print('process {} running in pid {} done'.format(self.name, self.pid))
for _ in range(2):
p = MyProcess()
p.start()
I get the following output:
process MyProcess-1 running in pid 65975
got foo 4322815784
foo's name is MYPROCESS-1
process MyProcess-2 running in pid 65976
got foo 4322815784
foo's name is MYPROCESS-2
process MyProcess-1 running in pid 65975 done
process MyProcess-2 running in pid 65976 done
I was expecting the second process to have a different instance of the class. How is get_foobar()
able to return the same instance of Foo
to each process?
EDIT / UPDATE: I am running this in python 3.5 on OSX and Ubuntu.