Are generator functions thread-safe?

Martin v. Loewis martin at v.loewis.de
Mon Sep 16 01:48:11 EDT 2002


"Robert Oschler" <Oschler at earthlink.net> writes:

> I know that a call to a generator function actually returns an independent
> iterator object (mea culpa if I'm wrong on this), but are there any hidden
> gotchas that would cause the use of the same generator function from
> multiple threads, to result in a sharing (especially local storage) or
> memory collision issue?

Terminology is tricky here: If you call a function that is a
generator, you get a generator object. So it is not clear to me
whether you have the same function in multiple threads, or the same
generator object.

If you access the same generator object from multiple threads, they
clearly share state.

If you call the same generator function from multiple threads, you get
a new generator object each time. You also get a new set of local
variables for each invocation. There is no "hidden" shared state. So
yes, generator functions are thread-safe.

Regards,
Martin




More information about the Python-list mailing list