放入和进入队列的不同对象

Different objects from putting and getting in queues

我正在尝试实现一个队列以在 Python 中的进程之间共享一些对象(例如列表)。但是,我放入队列的是和我之后得到的不同的对象:

from multiprocessing import Queue
q = Queue()
a = [1,2,3]
print(id(a)) # prints 4389597128
q.put(a)
b = q.get()
print(id(b)) # prints 4389600080

如果我使用数字等原子元素,则不会发生这种情况。

为什么会这样?如何将同一个对象放入队列中?

您看到此行为是因为 all objects added to a multiprocessing Queue are pickled when inserted, and unpickled when they are retrieved:

Note When an object is put on a queue, the object is pickled and a background thread later flushes the pickled data to an underlying pipe.

即使队列中的消费者 运行 与生产者在同一进程中,也会发生这种情况。默认情况下不会通过 pickling 保留对象的身份(尽管请参阅 this question 以了解可以通过自定义对象的 pickling 过程来尝试保留它的方法)。但是,如果可能的话,您最好调整您的实现,不要依赖 id 通过 pickling/unpickling 过程保持不变的对象。

你看到一些内置的不可变类型(如小整数)的 id 保持不变,因为 Python 在内部缓存这些实例,并且总是重复使用相同的实例。因此,unpickled int 最终成为对您放入队列中的完全相同 int 的引用。自定义类型不是这种情况。如果你尝试大量(Python 不缓存),你会看到从队列中拉出它后的 id 发生变化,就像自定义类型一样。