-
-
Save suenot/0dc7d179c3b5dcd4688cd8dce53f503b to your computer and use it in GitHub Desktop.
Python 3 asyncio basic producer / consumer example
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 asyncio | |
import random | |
q = asyncio.Queue() | |
async def producer(num): | |
while True: | |
await q.put(num + random.random()) | |
await asyncio.sleep(random.random()) | |
async def consumer(num): | |
while True: | |
value = await q.get() | |
print('Consumed', num, value) | |
loop = asyncio.get_event_loop() | |
for i in range(6): | |
loop.create_task(producer(i)) | |
for i in range(3): | |
loop.create_task(consumer(i)) | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment