Junior — Middle
Can you explain the principle of asynchronous methods in programming and how they differ from synchronous ones?
sobes.tech AI
Answer from AI
Asynchronous methods allow performing operations without blocking the main execution thread of the program. In Python, this is achieved using the keywords async and await.
How it works:
- An asynchronous method is declared with
async def. - Inside such a method, you can use
awaitto call other asynchronous operations that may take time (e.g., network requests, file reading). - When execution reaches
await, control returns to the calling code, allowing other tasks to run while waiting for the result.
Differences from synchronous methods:
- A synchronous method blocks execution until the operation completes.
- An asynchronous method allows the program to remain responsive and efficiently utilize waiting time.
Example:
import asyncio
async def fetch_data():
print("Starting download")
await asyncio.sleep(2) # simulate a long operation
print("Download complete")
async def main():
await fetch_data()
asyncio.run(main())
In this example, asyncio.sleep does not block the entire thread but allows other tasks to run during the wait.