Sobes.tech
Middle

What is the difference between asynchronous and parallel execution?

sobes.tech AI

Answer from AI

Asynchrony allows tasks to be performed interleaved, without blocking the main execution thread while waiting for resource-intensive operations (e.g., I/O) to complete. One task can pause, giving way to another, and then resume execution.

Parallelism involves the simultaneous execution of multiple tasks, usually on different processor cores. This is achieved using processes or threads.

Characteristic Asynchrony Parallelism
Execution Interleaved task execution Simultaneous task execution
Resources One thread/process (most often) Multiple threads/processes
Goal Efficient use of waiting time (I/O) Speeding up CPU-bound tasks
Mechanisms asyncio, await threading, multiprocessing
# Example of asynchrony
import asyncio

async def task1():
    print("Task 1 is running")
    await asyncio.sleep(1) # Simulate a long operation
    print("Task 1 completed")

async def task2():
    print("Task 2 is running")
    await asyncio.sleep(1) # Simulate a long operation
    print("Task 2 completed")

async def main():
    await asyncio.gather(task1(), task2()) # Run tasks asynchronously

if __name__ == "__main__":
    asyncio.run(main())
# Example of parallelism with threads
import threading
import time

def task1():
    print("Task 1 is running")
    time.sleep(1) # Simulate a long operation
    print("Task 1 completed")

def task2():
    print("Task 2 is running")
    time.sleep(1) # Simulate a long operation
    print("Task 2 completed")

thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("All tasks completed")