Pickle Queue objects in python

那年仲夏 提交于 2019-12-05 08:26:17

I suggest replacing your uses of Queue.Queue with collections.deque. The Queue class is intended to be used for synchronized communication between threads, so it will have some unnecessary overhead when used as a regular data structure. collections.deque is a faster alternative. (The name "deque" is pronounced "deck" and means "double-ended queue".)

The deque class does have a different API than the Queue type, but it should be pretty easy to translate between them. Use deque.append in place of Queue.put and deque.popleft in place of q.get() (or appendleft and pop, if you feel like going the other direction). Rather than calling Queue.empty, just use a deque instance as a Boolean value (like you do to test for an empty list).

deque instances are picklable:

>>> import collections, pickle
>>> q = collections.deque(["test"])
>>> pickle.dumps(q)
b'\x80\x03ccollections\ndeque\nq\x00]q\x01X\x04\x00\x00\x00testq\x02a\x85q\x03Rq\x04.'

As you have commented to @Blckknght, you don't need the synchronization features of Queue.Queue. So just use collections.deque that the Queue.Queue class uses itself as the underlying queue data structure. You will have to use .appendleft to emulate the FIFO Queue.put and .pop to emulate Queue.get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!