I'm trying to spawn child processes which return their results via a passed dict argument.
It appears to me that after Process.start()
is called that the passed dict is copied in some form because change in one is not reflected in the other. Yet, in both the parent and child process, id()
is the same value.
From this article, I would expect that id()
returns a unique value for an object.
https://www.programiz.com/python-programming/methods/built-in/id
The id() function returns identity of the object. This is an integer which is unique for the given object and remains constant during its lifetime.
import json
from multiprocessing import Process
from time import sleep
def my_format(obj):
return ('id(obj):' + str(id(obj)) +'; obj:' + json.dumps(obj, indent = 4))
def work(result):
result['child'] = 'only'
sleep(5)
# child does not see entry from parent, must be different object
# ie missing result['parent'] == 'only'
print('child thread: ' + my_format(result))
return
result = {}
p = Process(target = work, args = (result,))
result['both'] = 'see'
p.start() # fork(), which copies the object including its id()
result['parent'] = 'only'
sleep(5)
p.join()
# parent does not see entry from child, must be different object
# ie missing result['child'] == 'only'
print('main thread: ' + my_format(result))
Unexpectedly, the child result
and parent result
have diverged in content. I.e. changes in one is not reflected in the other.
child thread: id(obj):4385974824; obj:{
"both": "see",
"child": "only"
}
main thread: id(obj):4385974824; obj:{
"both": "see",
"parent": "only"
}