[英]How to put elements on bottom of Python queue
I've a queue that is populated by different threads. 我有一个由不同线程填充的队列。 I've a thread where I get items from the queue and I send them to another destination.
我有一个线程,从队列中获取项目,然后将它们发送到另一个目的地。 When the last operation fails I want to put again the elements in the queue, but in the bottom of the queue because I want that the dequeuer Thread dequeue them as first priority.
当最后一个操作失败时,我想再次将元素放入队列中,但要放在队列的底部,因为我希望出队线程将它们作为第一优先级出队。 Is there a way to do that?
有没有办法做到这一点? Maybe using other class instead of Queue.queue?
也许使用其他类而不是Queue.queue?
Here's an implementation -- it's basically Queue.put
method with self._put(item)
replaced by self.queue.appendleft(item)
这是一个实现-基本上是
Queue.put
方法,其中self._put(item)
替换为self.queue.appendleft(item)
from Queue import Queue
class MyQueue(Queue):
def putleft(self, item, block=True, timeout=None):
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self.queue.appendleft(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.