Clear all items from the queue
You just can not clear the queue, because every put also add the unfinished_tasks member.The join method depends on this value.And all_tasks_done needs to be notified also.
q.mutex.acquire()q.queue.clear()q.all_tasks_done.notify_all()q.unfinished_tasks = 0q.mutex.release()
or in decent way, use get and task_done pair to safely clear the tasks.
while not q.empty(): try: q.get(False) except Empty: continue q.task_done()
or just create a new Queue and delete old one.
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()