generators shared among threads

Alex Martelli aleaxit at yahoo.com
Tue Mar 7 10:21:41 EST 2006


<jess.austin at gmail.com> wrote:

> Thanks for the great advice, Alex.  Here is a subclass that seems to
> work:

You're welcome!

> from Queue import Queue
> from itertools import count
> 
> class reentrantQueue(Queue):
>     def _init(self, maxsize):
>         self.maxsize = 0
>         self.queue = []   # so we don't have to override put()
>         self.counter = count()
>     def _empty(self):
>         return False
>     def _get(self):
>         return self.counter.next()
>     def next(self):
>         return self.get()
>     def __iter__(self):
>         return self

You may also want to override _put to raise an exception, just to avoid
accidental misuse, though I agree it's marginal. Also, I'd use maxsize
(if provided and >0) as the upperbound for the counting; not sure that's
necessary but it seems pretty natural to raise StopIteration (rather
than returning the counter's value) if the counter reaches that
"maxsize". Last, I'm not sure I'd think of this as a reentrantQueue, so
much as a ReentrantCounter;-).


Alex



More information about the Python-list mailing list