Skip to content

Instantly share code, notes, and snippets.

@hryniuk
Created December 10, 2016 10:33
Show Gist options
  • Save hryniuk/69b93b62fe890eb655a24c2f7dfde9b6 to your computer and use it in GitHub Desktop.
Save hryniuk/69b93b62fe890eb655a24c2f7dfde9b6 to your computer and use it in GitHub Desktop.
Producer with slow consumer
import aiohttp
import asyncio
async def l(event, q):
while True:
# ok, I'm ready
event.set()
# get value to process
a = await q.get()
# process it
await asyncio.sleep(2)
print(a)
async def m(event, q):
i = 1
while True:
await asyncio.sleep(0.5)
# pass element to consumer, when it's ready
if event.is_set():
await q.put(i)
event.clear()
# produce value
i += 1
el = asyncio.get_event_loop()
ev = asyncio.Event()
qu = asyncio.Queue(5)
tasks = [
asyncio.ensure_future(l(ev, qu)),
asyncio.ensure_future(m(ev, qu))
]
el.run_until_complete(asyncio.gather(*tasks))
loop.close()
@hryniuk
Copy link
Author

hryniuk commented Dec 10, 2016

It work's because of await asyncio.sleep() call.

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