Created
December 10, 2016 10:33
-
-
Save hryniuk/69b93b62fe890eb655a24c2f7dfde9b6 to your computer and use it in GitHub Desktop.
Producer with slow consumer
This file contains hidden or 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 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It work's because of
await asyncio.sleep()
call.