Accessing a shared generator from multiple threads.

Josiah Carlson jcarlson at uci.edu
Wed Jan 21 16:17:00 EST 2004


Even easier:

Q = Queue.Queue()
Q.put(gen)
def thread():
    a = Q.get()
    use = a.next()
    Q.put(a)
    #do whatever you need

Of course you could just as easily use a single lock and a class:

class lockedgen:
    def __init__(self, gen):
        self.g = gen
        self.l = threading.Lock()
    def get(self):
        self.l.acquire()
        a = self.g.next()
        self.l.release()
        return a

generator = lockedgen(gen)
def thread():
    use = generator.get()
    #do what you need


 - Josiah



More information about the Python-list mailing list