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?
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():
The multiprocessing module has its own version of Queue that does include a
close
method. I am not sure how it works in threading, but its worth a try. I don't see why it shouldn't work the same:You could just catch the IOError as the close signal.
TEST
Though to be honest, its not too much different than setting a flag on the Queue.Queue. The multiprocessing.Queue is just using a closed file descriptor as a flag: