Sobes.tech
Middle+

What is the difference between synchronous and asynchronous programming?

sobes.tech AI

Answer from AI

Synchronous programming involves executing code sequentially: each operation blocks the execution of the next until it completes. Asynchronous programming allows launching operations without waiting for their completion and continuing with other tasks, which is especially useful when working with input/output or network requests.

In Python, asynchrony is implemented using the keywords async and await, enabling the writing of non-blocking code that uses resources more efficiently.

Example of an asynchronous function in Python:

import asyncio

async def fetch_data():
    print("Starting download...")
    await asyncio.sleep(2)  # simulate delay
    print("Data loaded")

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

asyncio.run(main())

Here, two tasks run in parallel without blocking each other, unlike the synchronous version.