Junior — Middle
How is asynchronous execution of tasks implemented in the Event Loop mechanism?
sobes.tech AI
Answer from AI
In Python, the execution of asynchronous tasks is managed through the Event Loop mechanism, which controls the event and task processing cycle. The Event Loop constantly checks the event queue and runs tasks that are ready to execute, without blocking the main thread.
Main components:
- Coroutines — functions that can suspend their execution (
await) to allow other tasks to run. - Futures — objects representing the result of an asynchronous operation that will be available later.
- Tasks — wrappers around coroutines that are scheduled and executed by the Event Loop.
Example using asyncio:
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(say_after(1, 'Hello'))
task2 = asyncio.create_task(say_after(2, 'World'))
print('Started tasks')
await task1
await task2
asyncio.run(main())
Here, the Event Loop manages the execution of coroutines, switching between them during waiting (await asyncio.sleep), allowing efficient asynchronous execution of multiple tasks.