Clear all items from the queue

前端 未结 3 1952
无人及你
无人及你 2020-12-13 03:48

How can I clear a queue. For example I have datas in a queue, but for some reason I don\'t need the existing data, and just want to clear the queue.

Is there any wa

3条回答
  •  借酒劲吻你
    2020-12-13 04:01

    This seems to do it pretty well for me. I welcome comments/additions in case I missed anything important.

    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()
    

提交回复
热议问题