Junior — Middle
How does the integration of a coroutine with the main event loop occur?
sobes.tech AI
Answer from AI
In Python, coroutines are integrated with the main event loop, which manages their execution and switching between them. The main loop runs coroutines, suspends their execution when waiting for asynchronous operations (like I/O), and resumes them when the operation completes.
For example, in asyncio, the event loop runs a coroutine that can use await to wait for another async operation. During waiting, the loop switches to other tasks, ensuring efficient resource use.
Example:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # suspends coroutine for 1 second
print("World")
async def main():
await say_hello()
asyncio.run(main())
Here, asyncio.sleep is an async delay that does not block the thread.