Skip to content

Instantly share code, notes, and snippets.

@ottolotto
Forked from hjwp/asyncio_prints.py
Created January 29, 2016 14:09
Show Gist options
  • Select an option

  • Save ottolotto/3253d77e9cd283234dc4 to your computer and use it in GitHub Desktop.

Select an option

Save ottolotto/3253d77e9cd283234dc4 to your computer and use it in GitHub Desktop.
an illustration of the difference between "yield from" and "create_task" in asyncio
import asyncio
import random
@asyncio.coroutine
def print_whenever(identifier):
"""a little function that prints at random intervals"""
while True:
yield from asyncio.sleep(random.choice([0.5, 1, 1.3]))
print('hi from', identifier)
@asyncio.coroutine
def start_things():
"""start several little printey functions at the same time"""
for i in range(5):
# this works - it kicks off our printer "in the background"
asyncio.get_event_loop().create_task(
print_whenever(i)
)
# this doesn't -- it never gets past the first item
# yield from print_whenever(i)
# tell asyncio to start running start_things
loop = asyncio.get_event_loop()
loop.create_task(start_things())
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment