Skip to content
Python

Coroutine

Basic usage of coroutines.

By EZ4Code Team
coroutinecoroutine

Code

import asyncio

async def producer(queue):
    for i in range(5):
        await asyncio.sleep(0.1)
        await queue.put(i)
    await queue.put(None)  # End signal

async def consumer(queue):
    while True:
        item = await queue.get()
        if item is None:
            break
        print(f"Consumed: {item}")
        queue.task_done()

async def main():
    q = asyncio.Queue()
    await asyncio.gather(producer(q), consumer(q))

asyncio.run(main())

Explanation

Coroutines implement cooperative concurrency via async/await, suitable for IO-intensive tasks.

More Python Snippets