generators shared among threads
Alan Kennedy
alanmk at hotmail.com
Sun Mar 5 09:14:47 EST 2006
[jess.austin at gmail.com]
> def f()
> i = 0
> while True:
> yield i
> i += 1
> g=f()
>
> If I pass g around to various threads and I want them to always be
> yielded a unique value, will I have a race condition?
Yes.
Generators can be shared between threads, but they cannot be resumed
from two threads at the same time.
You should wrap it in a lock to ensure that only one thread at a time
can resume the generator.
Read this thread from a couple of years back about the same topic.
Suggested generator to add to threading module.
http://groups.google.com/group/comp.lang.python/browse_frm/thread/76aa2afa913fe4df/a2ede21f7dd78f34#a2ede21f7dd78f34
Also contained in that thread is an implementation of Queue.Queue which
supplies values from a generator, and which does not require a separate
thread to generate values.
HTH,
--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
More information about the Python-list
mailing list