Coroutine
Asyncio By Example: Implementing the Producer-Consumer Pattern
python coroutine techThe Most Basic Case
With corountines, we can define a produer and consumer without any need for threads. This simplifies our code and makes it more efficient.
import asyncio
async def producer():
for i in range(6):
await asyncio.sleep(0.2)
yield i
async def consumer():
async for i in producer():
print(i)
async def main():
await asyncio.gather(consumer())
asyncio.run(main())
0
1
2
3
4
5
Work with Heavy IO
When working with heavy IO operations, we need to be careful not to block the event loop. Running heavy IO operations can block the current event loop, which would slow down the scheduling of all coroutines.