gpt4 book ai didi

python - 为什么多个进程在python中具有相同的对象ID

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:25 27 4
gpt4 key购买 nike

代码如下:

class T1():
def mytest(self,obj):
print id(obj)

if __name__=='__main__':
obj = {'a':'b'}
t1 = T1()
p1 = Process(name='p1',target=t1.mytest,args=(obj))
p1.start()
p2 = Process(name='p2',target=t1.mytest,args=(obj))
p2.start()

上面的代码打印出相同的id,是不是两个进程共享同一个对象?另一个问题,当我将 dict 更改为另一个常规对象时,它会抛出异常:TypeError: 'Test' object is not iterable
请问如何在 python 进程之间共享常规对象。

最佳答案

The above code print out the same id, are the two process sharing the same object?

不,标识符只保证对于给定进程是唯一的。在您的情况下,两个不同进程中的两个对象恰好具有相同的标识符,因为这两个进程执行相同的代码(无法保证这种行为,它发生的可能性很高)。

Another question when I change the dict to another regular object, it would throw exception as:TypeError: 'Test' object is not iterable How can I share a regular object between python processes please.

args 需要一个可迭代的参数。 (obj) 等同于 obj,因此如果 obj 不是可迭代对象,则会出现此错误。我猜你想写的是 (obj,),它会创建一个元组,在这种情况下 obj 可以是任何对象(只要当然,它可以腌制)。

关于python - 为什么多个进程在python中具有相同的对象ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33817442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com