Skip to content

Instantly share code, notes, and snippets.

@dyerw
Created January 6, 2015 17:09
Show Gist options
  • Save dyerw/3d53e7cd94f05cc92c1c to your computer and use it in GitHub Desktop.
Save dyerw/3d53e7cd94f05cc92c1c to your computer and use it in GitHub Desktop.
A simple producer/consumer example using python coroutines
import random
def coroutine(func):
"""A decorator to automatically prime coroutines"""
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
@coroutine
def consumer():
"""Tells us if a number is 2 or not"""
# Wait here until we get sent something
while True:
num = yield
if num == 2:
print("The number {} is 2".format(num))
else:
print("The number {} is not 2".format(num))
def producer(consumer):
"""Produces random numbers up to 20"""
while True:
# Produce a random number and send it to the consumer
r = random.randint(0, 20)
consumer.send(r)
# Wait here until next() is called
yield
if __name__ == "__main__":
# Set up generators
c = consumer()
p = producer(c)
# Produce 10 random numbers
for _ in range(10):
next(p)
@jxltom
Copy link

jxltom commented Sep 27, 2017

I am curious how to make this to multiple producers and consumers?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment