Sobes.tech
Middle

What is the difference between synchronous and asynchronous execution?

sobes.tech AI

Answer from AI

Synchronous execution means that tasks are performed sequentially: the next task starts only after the current one is completed. In this mode, the program blocks, waiting for the result of an operation, such as reading a file or a network request.

Asynchronous execution allows tasks to be started without waiting for their completion, and to continue working. The result of the operation is processed later, when it becomes available, which increases efficiency when working with input-output and multitasking.

An example in Python using asyncio:

import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print('Starting')
    await say_after(1, 'Hello')  # wait synchronously
    await say_after(1, 'World')  # then the next

asyncio.run(main())

Here, tasks are executed sequentially. If you run them simultaneously:

async def main():
    print('Starting')
    await asyncio.gather(
        say_after(1, 'Hello'),
        say_after(1, 'World')
    )

asyncio.run(main())

Both tasks will run in parallel, and the output will appear for both after about 1 second.