Python

Python Concurrency Explained: Asyncio vs. Threading vs. Multiprocessing

Have you ever written a Python script that makes 100 API requests, downloads multiple files, or processes thousands of records, only to find that it takes much…

D
DevByteTechnical Author
Published
16 min read2 views
Python Concurrency Explained: Asyncio vs. Threading vs. Multiprocessing

Have you ever written a Python script that makes 100 API requests, downloads multiple files, or processes thousands of records, only to find that it takes much longer than expected?

The first thing many developers try is adding more threads or switching to asynchronous code. Sometimes it works really well. Other times, the application becomes more complicated without any noticeable improvement in performance.

The problem is that not every task benefits from the same concurrency approach.

Python provides several ways to execute multiple tasks efficiently, including asyncio, threading, and multiprocessing. Although all three can help improve performance, they work differently and solve different problems.

For example, if your application spends most of its time waiting for API responses, asynchronous programming can help it handle multiple requests without waiting for each one to finish. If you're working with a blocking library, threads might be a better option. If you're performing expensive calculations, multiple processes can make better use of multiple CPU cores.

In this article, we'll understand how these approaches work, implement each one with practical examples, compare their performance characteristics, and discuss how to choose the right option for real-world Python applications.

What Is Concurrency in Python?

Concurrency means structuring a program so that multiple tasks can make progress during overlapping periods of time.

Consider an application that needs to fetch information from three external APIs.

A synchronous implementation might look like this:

import time


def fetch_data(name):
    print(f"Fetching {name}...")
    time.sleep(2)
    print(f"Finished {name}")


start = time.perf_counter()

fetch_data("API 1")
fetch_data("API 2")
fetch_data("API 3")

print(f"Total time: {time.perf_counter() - start:.2f} seconds")

Each operation takes approximately two seconds, so the total execution time will be around six seconds.

The application waits for the first operation to finish before starting the second one. It then waits for the second operation before starting the third.

Now imagine that each operation represents a network request. While the application waits for the first server to respond, the CPU is not necessarily doing useful work for that request.

This is where concurrency becomes useful.

Instead of waiting for every operation individually, we can arrange for multiple operations to be in progress at the same time.

There are two important terms to understand:

  • Concurrency: Multiple tasks make progress during overlapping periods.

  • Parallelism: Multiple tasks execute at the same instant, typically using different CPU cores.

Concurrency does not always mean that code is running on multiple CPU cores. An asynchronous application can manage many network operations on a single thread by switching between tasks whenever they are waiting.

Python supports several concurrency models, and choosing between them depends on what your application actually does.

Understanding I/O-Bound and CPU-Bound Tasks

Before comparing asyncio, threading, and multiprocessing, it helps to understand the type of work being performed.

I/O-bound tasks

An I/O-bound task spends a significant amount of time waiting for an external operation.

Common examples include:

  • Calling REST APIs.

  • Downloading files.

  • Reading data from a database.

  • Uploading files to cloud storage.

  • Communicating with external services.

  • Reading and writing files.

Suppose your application sends a request to an external API and waits 800 milliseconds for the response.

During that time, the application does not need to continuously execute Python instructions for that request. It can work on another request instead.

This is why asynchronous programming and threading are often useful for I/O-bound workloads.

CPU-bound tasks

A CPU-bound task spends most of its time performing calculations.

Examples include:

  • Image processing.

  • Processing large datasets.

  • Compressing files.

  • Running computational algorithms.

  • Performing expensive transformations.

  • Generating computationally intensive reports.

Consider a function that calculates a large number of mathematical operations. There is no external server to wait for. The function needs CPU time to complete its work.

Using asyncio alone will not make this calculation run faster because there is no natural I/O wait at which another task can take over.

For CPU-heavy work, multiprocessing is often a better starting point in standard CPython builds.

With that distinction in mind, let's look at each approach.

1. Python Threading: Running Tasks in Multiple Threads

Threading allows multiple threads to operate within the same process.

Threads share the process's memory, which makes it relatively straightforward to share objects between them. However, shared mutable state must be handled carefully because multiple threads can access the same data.

Python provides the built-in threading module for creating and managing threads.

Threading is especially useful when you need to perform multiple blocking operations concurrently, such as making network requests with a synchronous HTTP client.

Example: Downloading data with threading

Imagine that you need to fetch data from several APIs using a synchronous HTTP client.

For demonstration purposes, we'll simulate network requests with time.sleep().

import threading
import time


def fetch_data(api_name):
    print(f"Starting {api_name}")

    # Simulate waiting for a network response
    time.sleep(2)

    print(f"Finished {api_name}")


start = time.perf_counter()

threads = []

for i in range(5):
    thread = threading.Thread(
        target=fetch_data,
        args=(f"API {i + 1}",)
    )

    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print(f"Total time: {time.perf_counter() - start:.2f} seconds")

Each task waits for approximately two seconds.

Because the threads can wait concurrently, the total execution time should be closer to two seconds than ten seconds, although the exact result depends on system overhead and scheduling.

Let's understand the important methods.

threading.Thread()

Creates a new thread and specifies the function that should run inside it.

start()

Starts the thread. Calling the function directly would execute it in the current thread instead.

join()

Waits for the thread to finish before the program continues.

Without the join() calls, the main thread could reach the end of the script before all the intended work has completed.

When should you use threading?

Threading makes sense when:

  • You're using a synchronous HTTP library.

  • You need to process multiple files concurrently.

  • Your application performs blocking I/O.

  • You want a relatively simple way to run background operations within one process.

However, starting hundreds or thousands of threads without limits can create significant overhead.

For a large number of tasks, a thread pool is often a better choice.

Using ThreadPoolExecutor

Python's concurrent.futures module provides ThreadPoolExecutor, which manages a pool of worker threads.

Instead of manually creating a thread for every task, you can submit work to the pool.

from concurrent.futures import ThreadPoolExecutor
import time


def fetch_data(api_name):
    print(f"Fetching {api_name}")

    time.sleep(2)

    return f"Data received from {api_name}"


api_names = [
    "API 1",
    "API 2",
    "API 3",
    "API 4",
    "API 5",
]

start = time.perf_counter()

with ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(fetch_data, api_names))

for result in results:
    print(result)

print(f"Total time: {time.perf_counter() - start:.2f} seconds")

Here, max_workers=5 allows up to five tasks to execute concurrently through the pool.

The context manager waits for the executor's work to finish before exiting.

One useful detail is that executor.map() returns results in the order of the input iterable, even if tasks complete in a different order.

For larger workloads, use a sensible worker limit rather than submitting unlimited work to an unrestricted number of threads.

2. Python Multiprocessing: Using Multiple Processes

Threading is not always the right solution.

If you're processing images, performing mathematical calculations, or transforming large datasets, you may want to execute CPU-heavy work across multiple CPU cores.

Python's multiprocessing module allows you to create separate processes.

Each process has its own Python interpreter and memory space. This provides better isolation than threads, but passing data between processes can introduce serialization and communication overhead.

In standard GIL-enabled CPython builds, multiprocessing is a common way to achieve CPU parallelism for Python code.

What is the Global Interpreter Lock?

The Global Interpreter Lock, commonly called the GIL, is a mechanism in standard CPython builds that generally allows only one thread at a time to execute Python bytecode within an interpreter.

This means that creating multiple threads does not automatically allow CPU-intensive Python code to run in parallel across multiple cores.

Threads can still be useful for I/O-bound work because the interpreter can switch between threads while operations wait, and many I/O operations release the GIL.

The GIL is an implementation detail of CPython, not a universal rule for every Python implementation or build. Modern Python also offers optional free-threaded builds, which change these trade-offs.

For the common GIL-enabled CPython configuration, multiprocessing is a practical approach when CPU-bound work needs to run in parallel.

Example: Processing numbers with multiprocessing

Let's create a function that performs an expensive calculation.

def calculate_sum(n):
    total = 0

    for i in range(n):
        total += i * i

    return total

We can run this function using multiple processes.

Create a file named multiprocessing_example.py:

from multiprocessing import Pool
import time


def calculate_sum(n):
    total = 0

    for i in range(n):
        total += i * i

    return total


if __name__ == "__main__":
    numbers = [
        2_000_000,
        2_000_000,
        2_000_000,
        2_000_000,
    ]

    start = time.perf_counter()

    with Pool(processes=4) as pool:
        results = pool.map(calculate_sum, numbers)

    print(results)
    print(f"Total time: {time.perf_counter() - start:.2f} seconds")

The pool creates four worker processes and distributes the calculations across them.

The if __name__ == "__main__": guard is important, especially on platforms that start worker processes using the spawn method.

Without the guard, a child process may execute the module's startup code again, potentially causing recursive process creation.

The function must also be accessible to the worker processes, and its arguments and return values generally need to be serializable.

When should you use multiprocessing?

Multiprocessing is worth considering when:

  • Your workload involves expensive Python calculations.

  • Tasks can be divided into independent units of work.

  • You want to use multiple CPU cores.

  • The cost of starting processes and passing data is reasonable compared with the work being performed.

There are trade-offs.

Processes use additional memory and have startup costs. Passing a large object between processes can be expensive because the object may need to be serialized and copied.

For a small calculation, multiprocessing may actually be slower than a normal function call.

Measure the performance of the complete workload rather than assuming more processes always mean better performance.

3. Python Asyncio: Handling Many I/O Operations Asynchronously

Now let's look at asyncio.

Unlike traditional threading, asyncio uses an event loop to schedule asynchronous tasks. A task can pause at an await expression while waiting for an operation to complete, allowing the event loop to run other ready tasks.

This approach can handle many concurrent I/O operations without creating a separate operating-system thread for every task.

It is especially useful when your application relies on libraries that support asynchronous I/O.

Understanding async and await

Consider this function:

import asyncio


async def fetch_data(api_name):
    print(f"Fetching {api_name}")

    await asyncio.sleep(2)

    print(f"Finished {api_name}")


async def main():
    await asyncio.gather(
        fetch_data("API 1"),
        fetch_data("API 2"),
        fetch_data("API 3"),
    )


asyncio.run(main())

The async def syntax defines a coroutine function.

Calling a coroutine function produces a coroutine object; it does not immediately execute the function like a normal function call.

await suspends the current coroutine while the awaited operation is in progress, allowing the event loop to run other tasks.

asyncio.gather() schedules the supplied awaitables and waits for their results.

asyncio.run() creates an event loop, executes the main coroutine, and manages the loop's lifecycle.

Because the three operations spend most of their time waiting, the total execution time should be close to two seconds rather than six seconds.

Notice that this example uses asyncio.sleep(), not time.sleep().

That difference matters.

Calling time.sleep() inside an asynchronous task blocks the event-loop thread. Other tasks on that loop cannot make progress until the blocking call returns.

Real-world example: Fetching multiple APIs

In a real application, you might use an asynchronous HTTP client such as HTTPX.

Install it:

pip install httpx

Now create a script:

import asyncio
import httpx


async def fetch_url(client, url):
    try:
        response = await client.get(url, timeout=10.0)
        response.raise_for_status()

        return {
            "url": url,
            "status": response.status_code,
            "success": True,
        }

    except httpx.HTTPError as error:
        return {
            "url": url,
            "error": str(error),
            "success": False,
        }


async def main():
    urls = [
        "https://example.com",
        "https://httpbin.org/get",
        "https://www.python.org",
    ]

    async with httpx.AsyncClient() as client:
        results = await asyncio.gather(
            *(fetch_url(client, url) for url in urls)
        )

    for result in results:
        print(result)


if __name__ == "__main__":
    asyncio.run(main())

This example reuses one asynchronous HTTP client and fetches multiple URLs concurrently.

Each request has a timeout, and HTTP errors are handled separately so one failed request does not automatically prevent the other results from being printed.

For a real application, you should also consider retry policies, rate limits, connection limits, and the behavior of the external services you're calling.

Limit concurrency for large workloads

The previous example is fine for a small list of URLs. However, what happens if you need to process 50,000 URLs?

Creating tasks for all 50,000 URLs at once can consume substantial memory and overwhelm the remote service.

A semaphore can limit the number of operations running at a time.

import asyncio


async def fetch_data(item, semaphore):
    async with semaphore:
        print(f"Processing {item}")

        await asyncio.sleep(1)

        return f"Processed {item}"


async def main():
    semaphore = asyncio.Semaphore(10)

    tasks = [
        fetch_data(item, semaphore)
        for item in range(100)
    ]

    results = await asyncio.gather(*tasks)

    print(f"Processed {len(results)} items")


asyncio.run(main())

In this example, at most ten tasks can be inside the semaphore-protected section at once.

The example still creates 100 task objects, so for extremely large or unbounded workloads, a bounded queue with a fixed number of worker coroutines is often more memory-efficient.

The same idea applies to API requests, database operations, and file uploads: concurrency should be controlled according to the available resources and the limits of the services you're using.

When should you use asyncio?

Consider asyncio when:

  • You need to manage many simultaneous network requests.

  • You're building an asynchronous API client.

  • Your framework and database drivers support asynchronous operations.

  • You need WebSocket connections or other long-lived I/O operations.

  • You want to handle many waiting tasks without creating a large number of threads.

However, asynchronous code is not automatically faster.

If most of your application uses blocking libraries, converting a few functions to async def will not make those libraries non-blocking.

You need to use asynchronous APIs or deliberately move blocking work to a thread or process pool.

Asyncio vs. Threading vs. Multiprocessing

Let's compare the three approaches.

Feature

Asyncio

Threading

Multiprocessing

Main execution model

Event loop and coroutines

Multiple threads

Multiple processes

Memory model

Tasks usually share the event loop's process memory

Threads share process memory

Processes have separate memory spaces

Best starting point

Async-compatible I/O workloads

Blocking I/O workloads

CPU-intensive workloads

CPU parallelism in standard GIL-enabled CPython

Not from one event loop alone

Limited for Python bytecode by the GIL

Yes, using separate processes

Startup and coordination overhead

Usually low per task

Thread management overhead

Higher process and communication overhead

Shared-state risks

Can occur between tasks when operations interleave

Race conditions and synchronization issues

Requires explicit communication or shared-memory mechanisms

Typical use case

Concurrent API requests

Blocking network or file operations

Parallel calculations or independent data processing

The key takeaway is that these approaches are not interchangeable in every situation.

asyncio is a strong option for high-concurrency I/O. Threading is useful when working with blocking operations. Multiprocessing is often better suited to CPU-heavy tasks.

Practical Benchmark: Comparing the Three Approaches

Let's run a simple benchmark using simulated I/O.

The example below compares synchronous execution, threading, and asyncio.

import asyncio
import time
from concurrent.futures import ThreadPoolExecutor


def sync_task():
    time.sleep(1)


def threading_benchmark():
    with ThreadPoolExecutor(max_workers=5) as executor:
        list(executor.map(lambda _: sync_task(), range(5)))


async def async_task():
    await asyncio.sleep(1)


async def asyncio_benchmark():
    await asyncio.gather(
        *(async_task() for _ in range(5))
    )


if __name__ == "__main__":
    start = time.perf_counter()

    for _ in range(5):
        sync_task()

    print(
        "Synchronous:",
        round(time.perf_counter() - start, 2),
        "seconds",
    )

    start = time.perf_counter()
    threading_benchmark()

    print(
        "Threading:",
        round(time.perf_counter() - start, 2),
        "seconds",
    )

    start = time.perf_counter()
    asyncio.run(asyncio_benchmark())

    print(
        "Asyncio:",
        round(time.perf_counter() - start, 2),
        "seconds",
    )

With each task waiting for one second, you should see a pattern similar to this:

Approach

Approximate time

Synchronous

5 seconds

Threading

1 second

Asyncio

1 second

These are illustrative expectations, not measured benchmark results. Actual execution times vary by system and workload.

The example also does not benchmark multiprocessing, because time.sleep() does not perform CPU-intensive work. Using processes for a simple sleep operation would mostly measure process overhead rather than useful CPU parallelism.

For a meaningful CPU benchmark, compare a normal sequential calculation with the same independent calculations executed through a process pool. Use sufficiently large tasks to make process startup and communication overhead relatively small.

The most important lesson is that benchmark results depend on the workload. A result from an artificial sleep test does not prove that asyncio is faster than threading for every real application.

Common Mistakes Developers Make

Concurrency can improve performance, but it also introduces problems that are easy to overlook.

1. Using Asyncio with Blocking Functions

Consider this code:

import asyncio
import time


async def process_task():
    time.sleep(3)

Although the function is declared with async def, time.sleep(3) blocks the event-loop thread.

Other tasks on that loop cannot run during the sleep.

For asynchronous delays, use:

await asyncio.sleep(3)

For blocking functions that cannot easily be replaced with asynchronous alternatives, consider running them through asyncio.to_thread() or an appropriate executor.

2. Assuming Threads Always Make Python Code Faster

Threads are useful for overlapping I/O waits, but standard GIL-enabled CPython does not generally execute CPU-bound Python bytecode in parallel across multiple threads.

If your workload is CPU-heavy, benchmark multiprocessing or other suitable approaches instead.

3. Creating Too Many Tasks or Workers

Unlimited concurrency can exhaust memory, create too many open connections, overwhelm a database, or trigger external API rate limits.

Use bounded queues, semaphores, thread pools, or process pools to control how much work runs simultaneously.

4. Ignoring Shared-State Problems

Threads can access the same mutable objects, and concurrent updates can produce race conditions.

Use locks, thread-safe queues, or other synchronization mechanisms when necessary.

With asyncio, tasks on a single event loop do not ordinarily execute Python instructions simultaneously, but race-like bugs can still occur when a task suspends between related operations.

5. Forgetting Error Handling and Cancellation

Concurrent tasks can fail independently. A production application needs a clear policy for timeouts, retries, cancellation, partial results, and cleanup.

For example, a failed external API request should not automatically cause an entire batch operation to fail unless that is the behavior your application requires.

Choose the appropriate task-management tools and test failure scenarios, not just successful execution.

How to Choose the Right Approach for Your Project

When deciding between these approaches, start by identifying where your application spends most of its time.

Choose asyncio if:

You're building an asynchronous API client, WebSocket service, or backend that needs to handle many concurrent I/O operations. Your database drivers and other dependencies should support asynchronous operation if you want to benefit from it.

Choose threading if:

You're using synchronous libraries and want to overlap blocking I/O operations without rewriting the entire application around an event loop.

Choose multiprocessing if:

You're processing large datasets, performing expensive calculations, or running independent CPU-intensive tasks that can benefit from multiple cores.

Use a combination if necessary.

Real applications often have mixed workloads.

For example, an API service might use asyncio for network requests, offload a blocking library to a thread pool, and send expensive image-processing jobs to a separate worker process or task queue.

There is no requirement to use only one concurrency model throughout an entire project. The important thing is to choose each tool deliberately and manage the complexity it introduces.

Final Thoughts

Python provides several ways to handle multiple tasks efficiently, but understanding when to use each approach matters more than memorizing the syntax.

asyncio helps manage concurrent I/O operations through an event loop. Threading allows multiple threads to work within one process and is useful for blocking I/O. Multiprocessing uses separate processes and is often a good fit for CPU-intensive work.

Before changing your application, profile it and identify the actual bottleneck. A slow database query, an inefficient algorithm, or an external API with high latency may be the real problem. Concurrency can help, but it will not automatically fix inefficient code or an overloaded dependency.

My recommendation is to start with the simplest implementation that meets your performance requirements. Measure it, identify the bottleneck, and introduce concurrency where it provides a clear benefit.

Once you understand the difference between I/O-bound and CPU-bound work, choosing between asyncio, threading, and multiprocessing becomes much easier.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘