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?
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() .
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().
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.
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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With