Sobes.tech
Junior

What is asynchronous programming?

sobes.tech AI

Answer from AI

Asynchronous programming is a execution model that allows a program "not to wait" for the completion of a long-running operation (such as input/output), but to perform other useful tasks in the meantime. It is based on the concept of a single thread of execution that manages multiple tasks using cooperative multitasking or event loops.

Main advantages:

  • Increased performance and responsiveness in applications with a large number of input/output operations or network requests.
  • Efficient resource utilization (less overhead compared to multithreading).
  • Simplified code writing for parallel operations compared to manual thread management.

Main concepts in Python:

  • async def: Keyword for defining an asynchronous function or coroutine.
  • await: Keyword used inside an asynchronous function to suspend its execution until the asynchronous operation completes.
  • asyncio: Built-in Python library for writing single-threaded concurrent code using coroutines, multiplexing I/O through sockets and other resources, launching subprocesses, and scheduling tasks.
  • Event Loop: The main component of asyncio that manages the execution of coroutines, handles events (such as socket readiness for reading/writing), and switches execution between coroutines.

Example of using asyncio:

import asyncio

async def task_one():
    # Simulate a long operation
    await asyncio.sleep(1)
    print("Task one completed")

async def task_two():
    # Simulate another long operation
    await asyncio.sleep(2)
    print("Task two completed")

async def main():
    # Run tasks concurrently
    await asyncio.gather(task_one(), task_two())

# Run the main event loop
if __name__ == "__main__":
    asyncio.run(main())

In this example, although task_two takes longer, both tasks are launched and executed concurrently, without blocking each other during waiting.

Differences from multithreading:

  • Multithreading: Uses multiple operating system threads. Each thread can execute code simultaneously on different CPU cores (parallelism). Data exchange between threads requires complex synchronization mechanisms (locks). Python is limited by GIL for CPU-bound tasks.
  • Asynchronous programming: Uses a single thread of execution that switches between tasks when they "wait" for something (concurrency). Suitable for I/O-bound tasks. Fewer issues with race conditions, but requires task cooperation (using await).