Created
January 6, 2015 17:09
-
-
Save dyerw/3d53e7cd94f05cc92c1c to your computer and use it in GitHub Desktop.
A simple producer/consumer example using python coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am curious how to make this to multiple producers and consumers?