""" This is a simple example of the Producer/Consumer problem in Python. It makes use of py.magic.greenlet: """ from py.magic import greenlet from Queue import Queue import time class Producer(object): def __init__(self, buffer, name, limit=10): self.buffer = buffer self.name = name self.limit = limit def run(self): """The resumable callback.""" for i in range(self.limit): self.buffer.put(i) # it blocks until there's room for the value time.sleep(1) print "%s has put %d in the buffer." % (self.name, i) cons.switch() # this is needed to pass control to the consumer class Consumer(object): def __init__(self, buffer, name): self.buffer = buffer self.name = name def run(self): while self.buffer.qsize(): data = self.buffer.get() # it blocks until some value is available time.sleep(1) print "%s has got %d from the buffer." % (self.name, data) prod.switch() # pass control to the producer time.sleep(0.5) print "%s is doing something with %s" % (self.name, data) prod.switch() # pass it again after value 'processing' if __name__ == '__main__': buffer = Queue() prod = greenlet(Producer(buffer, "Producer").run) cons = greenlet(Consumer(buffer, "Consumer").run) prod.switch()