Sobes.tech
Junior — Middle

How to implement a coroutine in programming?

sobes.tech AI

Answer from AI

In Python, coroutines are implemented using the keywords async and await. This allows writing asynchronous code that can pause and resume execution later without blocking the main thread.

Example of a simple coroutine:

import asyncio

async def say_hello():
    print("Hello!")
    await asyncio.sleep(1)  # simulate an asynchronous operation
    print("Coroutine finished")

async def main():
    await say_hello()

asyncio.run(main())

Here, say_hello is a coroutine that pauses for a second, allowing other tasks to run.

How to implement a coroutine in programming? — Python - sobes.tech