generators shared among threads

Alan Kennedy alanmk at
Sun Mar 5 15:14:47 CET 2006

[jess.austin at]
> 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?


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.

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.


alan kennedy
email alan:    

More information about the Python-list mailing list