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

标签 python

代码如下:

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/

相关文章:

python - 在 Python 中快速检查范围

python - 在 Selenium webdriver 中应用代理网关

python MySQLdb在尝试INSERT INTO表时得到无效语法

Python 网络/cidr 计算

python - 为什么在 upstart 服务或守护进程服务中使用 user nobody nogroup

python - 当我未超出速率限制时收到 Github APi 403 错误

python - pygame 一直陷入困境

python - 在 Atom 中编写 Python 代码时,是否有一种巧妙的方法来调试 Python 代码?

python - 需要在 Django 应用程序中编写 .wav 文件,但不能在 Heroku(或 S3)上编写

python,lxml检索列表中的所有元素