【发布时间】:2019-01-17 20:58:21
【问题描述】:
我正在尝试生成子进程,这些子进程通过传递的 dict 参数返回其结果。
在我看来,在调用 Process.start() 之后,传递的 dict 以某种形式复制,因为其中一个的更改不会反映在另一个中。然而,在父进程和子进程中,id() 是相同的值。
从这篇文章中,我希望id() 返回一个对象的唯一值。
https://www.programiz.com/python-programming/methods/built-in/id
id() 函数返回对象的标识。这是一个整数 这对于给定的对象是唯一的,并且在其期间保持不变 终生。
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))
没想到孩子result和家长result在内容上出现了分歧。 IE。一个中的变化不会反映在另一个中。
child thread: id(obj):4385974824; obj:{
"both": "see",
"child": "only"
}
main thread: id(obj):4385974824; obj:{
"both": "see",
"parent": "only"
}
【问题讨论】:
-
你在哪里有不同的对象?只有
result字典 -
印刷品显示它们有不同的内容
-
您在
print调用之间修改对象,但您没有创建新对象 -
sleep没关系 - 你仍然只有 一个 对象,所以它的id显然保持不变 -
对象
result是可变的。改变字典的内容不会改变它的身份。
标签: python