generators shared among threads

jess.austin at gmail.com jess.austin at gmail.com
Tue Mar 7 19:55:01 EST 2006


Paul wrote:
>    def f():
>        lock = threading.Lock()
>        i = 0
>        while True:
>            lock.acquire()
>            yield i
>            i += 1
>            lock.release()
>
> but it's easy to make mistakes when implementing things like that
> (I'm not even totally confident that the above is correct).

The main problem with this is that the yield leaves the lock locked.
If any other thread wants to read the generator it will block.  Your
class Synchronized fixes this with the "finally" hack (please note that
from me this is NOT a pejorative).  I wonder... is that future-proof?
It seems that something related to this might change with 2.5?  My
notes from GvR's keynote don't seem to include this.  Someone that
knows more than I do about the intersection between "yield" and
"finally" would have to speak to that.




More information about the Python-list mailing list