generators shared among threads

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


Bryan Olson <fakeaddress at nowhere.org> 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:
            lock.acquire()

            # sleep 1 sec on first iteration, then 0 seconds on next iteration
            time.sleep(delay.pop())
            count += 1
            yield count

            lock.release()

    def run():
        print gen.next()

    gen = make_gen()

    # start a thread that will lock the generator for 1 sec
    threading.Thread(target=run).start()

    # make sure first thread has a chance to get started
    time.sleep(0.2)

    # start second thread while the generator is locked
    threading.Thread(target=run).start()

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/threading.py", line 436, in __bootstrap
        self.run()
      File "/usr/lib/python2.3/threading.py", line 416, in run
        self.__target(*self.__args, **self.__kwargs)
      File "/usr/tmp/python-28906xpZ", line 18, in run
    ValueError: generator already executing

    1



More information about the Python-list mailing list