Sobes.tech
Junior — Middle

What methods of asynchronous programming are available in Python?

sobes.tech AI

Answer from AI

Python provides several methods for implementing asynchronous programming:

  1. asyncio module — a standard library for writing asynchronous code using async/await. It allows creating coroutines, tasks, and managing the event loop.

  2. Coroutines and async/await keywords — enable writing asynchronous code that looks like synchronous code but does not block execution.

  3. Modules for asynchronous input/output — for example, aiohttp for asynchronous HTTP requests, aiomysql for working with databases.

  4. Threads and processes — through threading and multiprocessing modules, parallel execution can be implemented, although this is not exactly asynchronous in the traditional sense.

Example of using asyncio:

import asyncio

async def say_hello():
    await asyncio.sleep(1)
    print("Hello, async world!")

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

asyncio.run(main())

This code runs two coroutines in parallel without blocking the main thread.