Accessing a shared generator from multiple threads.
Andrae Muys
amuys at shortech.com.au
Sun Jan 18 21:05:29 EST 2004
[Subject line changed to allow thread to be found more easily in
google-groups]
Alan Kennedy <alanmk at hotmail.com> wrote in message news:<400AB936.BA1D9D73 at hotmail.com>...
> [Alan Kennedy]
> >> I believe that the following definition of serialise will correct the
> >> problem (IFF I've understood the problem correctly :-)
> >>
It does look like the following version will work, I was too focused
on synchronising the underlying generator, and forgot that my code
also needed to be re-entrant. Thanks for catching my mistake.
> >> #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> >> import time
> >> import thread
> >> import threading
> >>
> >> class serialise:
> >> "Wrap a generator in an iterator for thread-safe access"
> >>
> >> def __init__(self, gen):
> >> self.lock = threading.Lock()
> >> self.gen = gen
> >>
> >> def __iter__(self):
> >> return self
> >>
> >> def next(self):
> >> self.lock.acquire()
> >> try:
> >> return self.gen.next()
> >> finally:
> >> self.lock.release()
>
> [Ype Kingma]
> > Looks like a candidate for inclusion in a standard library to me.
>
> Well, maybe :-)
>
> To be honest, I don't have the time to write test cases, docs and
> patches. So I think I'll just leave it for people to find in the
> Google Groups archives ...
>
Andrae Muys
More information about the Python-list
mailing list