I need to know when a Queue is closed and wont have more items so I can end the iteration.
I did it by putting a sentinel in the queue:
from Queue import Queue
class IterableQueue(Queue):
_sentinel = object()
def __iter__(self):
return self
def close(self):
self.put(self._sentinel)
def next(self):
item = self.get()
if item is self._sentinel:
raise StopIteration
else:
return item
Given that this is a very common use for a queue, isn't there any builtin implementation?
Use a while loop to iterate through a queue in Python, e.g. while not q. empty(): . The loop checks if the queue is not empty and iterates as long as there are items in the queue.
A queue is a collection of objects that supports fast first-in, first-out (FIFO) semantics for inserts and deletes. The insert and delete operations sometimes called enqueue and dequeue. Unlike lists or arrays, queues typically don't allow for random access to the objects they contain.
Yep, queue. get() will block only a thread where it was called.
A sentinel is a reasonable way for a producer to send a message that no more queue tasks are forthcoming.
FWIW, your code can be simplified quite a bit with the two argument form of iter():
from Queue import Queue
class IterableQueue(Queue):
_sentinel = object()
def __iter__(self):
return iter(self.get, self._sentinel)
def close(self):
self.put(self._sentinel)
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