generators shared among threads

Paul Rubin http
Mon Mar 13 08:36:45 CET 2006

Bryan Olson <fakeaddress at> writes:
> I have not found definitive answers in the Python doc. Both
> generators and threads keep their own line-of-control, and
> how they interact is not clear.

It looks to me like you can't have two threads in the same generator:

    import threading, time

    def make_gen():
        lock = threading.Lock()
        count = 0
        delay = [0,1]
        while True:

            # sleep 1 sec on first iteration, then 0 seconds on next iteration
            count += 1
            yield count


    def run():

    gen = make_gen()

    # start a thread that will lock the generator for 1 sec

    # make sure first thread has a chance to get started

    # start second thread while the generator is locked

raises ValueError:

    Python 2.3.4 (#1, Feb  2 2005, 12:11:53) 
    [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> ## working on region in file /usr/tmp/python-28906xpZ...
    >>> Exception in thread Thread-2:
    Traceback (most recent call last):
      File "/usr/lib/python2.3/", line 436, in __bootstrap
      File "/usr/lib/python2.3/", line 416, in run
        self.__target(*self.__args, **self.__kwargs)
      File "/usr/tmp/python-28906xpZ", line 18, in run
    ValueError: generator already executing


More information about the Python-list mailing list