Search code examples
pythonqueuetimeout

Add timeout argument to python's Queue.join()


I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet. What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass?


Solution

  • Subclassing Queue is probably the best way. Something like this should work (untested):

    def join_with_timeout(self, timeout):
        self.all_tasks_done.acquire()
        try:
            endtime = time() + timeout
            while self.unfinished_tasks:
                remaining = endtime - time()
                if remaining <= 0.0:
                    raise NotFinished
                self.all_tasks_done.wait(remaining)
        finally:
            self.all_tasks_done.release()