The docs (python 3.4) explain that with spawn
, "the child process will only inherit those resources necessary to run the process object's run()
method".
But which objects are "necessary"? The way I read it suggested to me that all the objects that can be reached from inside run()
are "necessary", including arguments passed as args
to Process.__init__
, plus whatever is stored in global variables, as well as classes, functions defined in global scope and their attributes. However, this is incorrect; the following code confirms that the objects stored in global variables aren't inherited:
# running under python 3.4 / Windows
# but behaves the same under Unix
import multiprocessing as mp
x = 0
class A:
y = 0
def f():
print(x) # 0
print(A.y) # 0
def g(x, A):
print(x) # 1
print(A.y) # 0; really, not even args are inherited?
def main():
global x
x = 1
A.y = 1
p = mp.Process(target = f)
p.start()
q = mp.Process(target = g, args = (x, A))
q.start()
if __name__=="__main__":
mp.set_start_method('spawn')
main()
Is there a clear rule that states which objects are inherited?
EDIT:
To confirm: running this on Ubuntu produces the same output. (Thanks to @mata for clarifying that I forgot add global x
to main()
. This omission made my example confusing; it would also affect the result if I were to switch 'spawn'
to 'fork'
under Ubuntu. I now added global x
to the code above.)