Are generator functions thread-safe?
Tim Peters
tim.one at comcast.net
Mon Sep 16 12:18:33 EDT 2002
[David Eppstein]
> Also, if a call to the generator object is running from one thread, you
> will get an exception if you attempt to simultaneously call it (e.g.
> from another thread). I don't know how thread-safe is the code that
> prevents the generator from being called twice simultaneously, though.
A generator-iterator has an internal "am I currently running?" flag that's
inspected and mutated under protection of the GIL, so it's thread-safe. The
flag is exposed as the gi_running attribute of a generator-iterator object,
although I haven't found a use for that yet <wink>:
>>> def g():
... print i.gi_running
... yield 42
...
>>> i = g()
>>> i.gi_running
0
>>> x = i.next()
1
>>> x
42
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
More information about the Python-list
mailing list