Sobes.tech
Junior — Middle

Can you explain how asynchronous task processing is implemented in Python and how it works?

sobes.tech AI

Answer from AI

Asynchronous task processing in Python is implemented using the asyncio module, which allows writing code that does not block execution while waiting for input/output or other long-running operations.

Main concepts:

  • Coroutines — functions declared with async def, which can be paused with await and resumed later.
  • Event loop — manages the execution of coroutines, schedules their start, and switches between them.

Example:

import asyncio

async def say_hello():
    print('Hello')
    await asyncio.sleep(1)  # simulate an asynchronous operation
    print('World')

async def main():
    await asyncio.gather(say_hello(), say_hello())

asyncio.run(main())

In this example, two say_hello coroutines are run in parallel, and during the asyncio.sleep wait, the event loop switches between them, not blocking the program execution.