Middle
What is asynchronous programming (async)?
sobes.tech AI
Answer from AI
Asynchronous programming is a paradigm that allows multiple tasks to be executed simultaneously without blocking the main thread of the program. This is achieved through efficient use of waiting times (for example, during input/output operations).
Main concepts:
- Coroutines: Special functions that can suspend their execution and resume later. Declared with
async def. - Event Loop: The main orchestrator that manages the execution of coroutines, monitors events, and switches between tasks when one is waiting.
- await: A keyword to suspend the execution of a coroutine until the awaited operation completes (for example, calling another coroutine or waiting for I/O to finish).
Example:
// Example of an asynchronous function
import asyncio
async def fetch_url(url):
print(f"Starting download: {url}")
await asyncio.sleep(2) // Simulate a long operation (e.g., network request)
print(f"Download completed: {url}")
async def main():
# Create tasks from coroutines
task1 = asyncio.create_task(fetch_url("http://example.com/page1"))
task2 = asyncio.create_task(fetch_url("http://example.com/page2"))
# Wait for both tasks to complete
await task1
await task2
// Run the event loop
if __name__ == "__main__":
asyncio.run(main())
Advantages:
- Increased performance: Especially for I/O-bound tasks (network requests, file operations).
- Better resource utilization: No need to create multiple threads or processes, reducing overhead.
- Maintaining responsiveness: The main thread is not blocked, which is important for interactive applications or servers.
Asynchronous programming is well-suited for:
- Web servers (e.g., using
asyncioorFastAPI). - Web scraping.
- Working with databases.
- Any tasks involving waiting for external resources.