【问题标题】:Meaning of id() and why different objects from Process fork have the same id() value?id() 的含义以及为什么来自 Process fork 的不同对象具有相同的 id() 值?
【发布时间】: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


【解决方案1】:

对象——关于它的一切,包括 ID——被复制到进程中。这与deepcopy 不同,后者会创建一个新对象。它是同一个对象复制到另一个内存空间。

有关更多信息,请参阅此答案:

python multiprocessing arguments: deep copy?

【讨论】:

  • 谢谢瑞克,一定是这个!
  • kaushikghose.wordpress.com/2016/08/26/…stackoverflow.com/questions/11055303/… 中有额外的相关资源。从本质上讲,这似乎是 CPython 如何实现多处理的产物,它使用 OS fork() 克隆整个 Python 解释器实例,它是内存空间,因此也是对象 ID。
  • 感谢您的帮助@Peteris。请对这个问题投赞成票(如果你正在阅读这篇文章,让它摆脱负面影响),因为我认为这对开发人员来说是一个有效的混淆。
  • @PeterWood 感谢您的反馈。我已经更新了问题。
  • @RazzleShazl 我想这取决于“相同”的定义。如果我们在一个多元宇宙中,隔壁宇宙中的 RickTeachey 将是“相同的”,只是在不同的宇宙中。这就是这里发生的事情。
猜你喜欢
  • 1970-01-01
  • 2013-05-19
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 2019-04-01
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多