Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 819
olamundo Avatar asked Oct 14 '09 06:10

olamundo


People also ask

What is queue join in Python?

Queue. join() is similar to Thread. join() which will block the main thread until all the tasks in the queue have been processed. But you don't have to create a worker list workers and do a loop in the end to join every thread, but just do a single queue. join() .

Is Python queue thread-safe?

Python provides a thread-safe queue in the queue. Queue class. A queue is a data structure on which items can be added by a call to put() and from which items can be retrieved by a call to get().

How do you clear the queue in Python?

To remove items from a queue in Python, we will be using the “get function”. See the Python Queue example given below. To make sure that our queue is empty, we can use the empty function which will return Boolean values.

Does Python have a built in queue?

Implementation using list. List is a Python's built-in data structure that can be used as a queue. Instead of enqueue() and dequeue(), append() and pop() function is used.


2 Answers

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()
like image 155
Lukáš Lalinský Avatar answered Sep 19 '22 15:09

Lukáš Lalinský


The join() method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count:

stop = time() + timeout
while q.unfinished_tasks and time() < stop:
    sleep(1)

This loop will exist either when the tasks are done or when the timeout period has elapsed.

Raymond

like image 35
Raymond Hettinger Avatar answered Sep 18 '22 15:09

Raymond Hettinger