""" This is a simple example of the Producer/Consumer problem in Python. It makes use of multitask module: """ import multitask class Producer(object): def __init__(self, buffer, name, limit=10): self.buffer = buffer self.name = name self.limit = limit def run(self): for i in range(self.limit): data = "'%s-%s'" % (self.name, i) # task will be resumed after data is in the buffer yield self.buffer.put(data) print "%s has put %s in the buffer." % (self.name, data) # the task will be resumed after 1 second yield multitask.sleep(1) class Consumer(object): def __init__(self, buffer, name): self.buffer = buffer self.name = name def run(self): while not self.buffer.empty(): # task will be resumed after an element is available in the queue data = (yield self.buffer.get()) print "%s has got %s from the buffer." % (self.name, data) yield multitask.sleep(1.5) print "%s is doing something with %s" % (self.name, data) def main(): buffer = multitask.Queue() prod = Producer(buffer, "Producer") cons = Consumer(buffer, "Consumer") multitask.add(prod.run()) multitask.add(cons.run()) multitask.run() if __name__ == '__main__': main()