清除queu中的所有项目

2024-03-28 05:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能排好队。例如,我在队列中有数据,但由于某些原因,我不需要现有数据,只想清除队列。

有什么办法吗?这行得通吗:

oldQueue = Queue.Queue()

Tags: 数据队列queue原因办法oldqueue行得通
3条回答
q = Queue.Queue()
q.queue.clear()

编辑 为了简洁明了,我省略了线程安全的问题,但是@D and是非常正确的,下面的更好。

q = Queue.Queue()
with q.mutex:
    q.queue.clear()

您只是不能清除队列,因为每次放置也会添加未完成的任务成员。 join方法取决于此值。 所有的任务也需要通知。

q.mutex.acquire()
q.queue.clear()
q.all_tasks_done.notify_all()
q.unfinished_tasks = 0
q.mutex.release()

或者以体面的方式,使用get和task完成对安全地清除任务。

while not q.empty():
    try:
        q.get(False)
    except Empty:
        continue
    q.task_done()

或者创建一个新队列并删除旧队列。

这对我来说似乎很好。如果我错过了重要的事情,我欢迎你的评论/补充。

class Queue(queue.Queue):
  '''
  A custom queue subclass that provides a :meth:`clear` method.
  '''

  def clear(self):
    '''
    Clears all items from the queue.
    '''

    with self.mutex:
      unfinished = self.unfinished_tasks - len(self.queue)
      if unfinished <= 0:
        if unfinished < 0:
          raise ValueError('task_done() called too many times')
        self.all_tasks_done.notify_all()
      self.unfinished_tasks = unfinished
      self.queue.clear()
      self.not_full.notify_all()

相关问题 更多 >