top of page

Four Ways to Do Many Things at Once I: Threads, Processes, and the GIL

Writer: Mic
Mic
Oct 13
5 min read

Updated: Oct 18

Python can’t do parallelism. Except when it can. Except when it can’t.

Everyone that looks into Python and parallel workflows eventually hears all three versions of this sentence. Usually in a very short period and from different more or less reputable sources.

This post aims to build one mental model that explains when each tool works, and why. It is neither a benchmark nor an exhaustive guide to concurrency theory. We will use one toy task, solve it four ways, and keep concurrent.futures as the common thread through all of them.

Part I covers threads and processes, and the infamous GIL that sits between them. Part II covers asyncio and the new free-threaded builds of Python, and what they do and don’t change.

I guess for ChatGPT, parallelism means ... octopus?

The Toy Task

Our task: fetch 50 pages and extract data from each.

We will use books.toscrape.com, a sandbox site built for exactly this kind of experiment. It has 50 catalogue pages, each listing 20 books.

One unit of work has two parts:

  1. Fetch the page. This is network I/O. Our program mostly waits.

  2. Parse the page. This is CPU work. Our program mostly computes.

Parsing 50 small pages is honestly too fast to notice. So we add a deliberately wasteful hashing loop to parse. It stands in for the heavy lifting you would do in real life: cleaning, scoring, feature extraction.

Three plain, synchronous functions. Boring, on purpose. Every approach below reuses these functions untouched. Only the scheduling changes.


The Baseline

Our simple workfow is now

Fifty pages, one after another. While we wait for page 7 to arrive, the CPU does nothing. While we hash page 7, the network does nothing. Running on an extra slow connection to simulate extra latency for the task, this clocks in for my tests at around 60 seconds.

Your network will differ, so treat all numbers in this post as shapes, not measurements.

Everything that follows is a way of removing that wasted time.


The GIL, in One Paragraph

The Global Interpreter Lock is a mutex inside CPython. Only one thread can execute Python bytecode at any moment.

That is the whole rule. Two consequences follow:

  • Threads cannot run Python code in parallel. Two threads doing arithmetic take turns.

  • A thread that is waiting (on a socket, a file, a sleep) releases the lock. Another thread runs in the meantime.

So the GIL doesn’t forbid concurrency. It forbids parallel computation inside one process.

That distinction explains the behaviour we will see throughout this series.


Threads: Waiting Together

Our fetch step spends nearly all of its time waiting, which suits threads well.

The diff from the baseline is two lines. The pool.map behaves like the built-in map. It returns results in input order. Exceptions are re-raised when you reach the failing result. The with block waits for everything to finish.

Ten threads means ten requests in flight. While one thread waits on the network, it has released the GIL, and the others make progress.

This goes down to between 7 and 8 second, even with the simulated slow network. An easy 8x speedup for two lines.

We got that speedup even though parse is CPU-bound. The hashing is still serialised by the GIL. We only parallelised the waiting.

What happens if there is nothing to wait for?


Proof by Failure

Let’s remove the network entirely and run pure computation.

Four countdowns, sequentially, then on four threads.

The threaded version is about as slow as the sequential one. Sometimes slightly slower, because the threads fight over the lock and pay for the context switching.

This is the “Python can’t do parallelism” half of the story. If your bottleneck is Python bytecode, more threads buy you nothing on a standard build.


Processes: Actual Parallelism

If one interpreter can only run one thread at a time, use more interpreters.

Each worker is a separate Python process with its own interpreter and its own GIL. On a machine with four or more cores, this runs close to four times faster than the sequential version.

That if name == "__main__": guard is not decoration. On Windows and macOS, worker processes are started by importing your script. Without the guard, each worker would try to start its own pool. Chaos follows.

Processes come with a serialisation cost.

Arguments and return values travel between processes via pickle. That has consequences:

  • Functions passed to the pool must be defined at module top level. No lambdas, no closures.

  • Arguments must be picklable. Open file handles and database connections are not.

  • Large results are copied, not shared. Returning a 500 MB DataFrame from a worker is a quiet way to lose all your gains.

And the same toy task, with processes:

This is a good result for CPU, and a mediocre one for I/O. We now have as many requests in flight as we have cores. Eight, maybe. We could have handled more of the waiting cheaply with threads.


The Common Thread

As you can see the thread and process versions are nearly the same code?

That is what makes concurrent.futures handy. ThreadPoolExecutor and ProcessPoolExecutor share one interface: submit, map, as_completed, and context-manager cleanup. Swapping one for the other is a one-word change.

So a tiny helper lets us compare approaches fairly:

In the next part, we will connect asyncio to this interface too. First, we can combine the two pools.

threads (10)            7.27s
threads (50)            3.85s
processes (cpu)         8.50s

Due the way we set up the different workloads, additional processes will nearly always loose out in the example. The parse step is simply not involved enough.


Both at Once

The fetch step wants threads and the parse step wants processes. We can give each its own pool.

The trick is that io_pool.map hands back an iterator. As each page arrives, cpu_pool.map picks it up and ships it to a worker process. Parsing starts while later pages are still downloading.

This also keeps session objects and connections out of the process boundary. Only the HTML string crosses it. The data we pickle is small and boring on purpose.

This is the most useful pattern in the post. Many real pipelines mix I/O and some form of offline computation, and a pool for each suits most of them.


When NOT to Use Them

Processes for tiny tasks. Starting a worker costs real time, and each task costs a pickle round trip. If the work takes microseconds, the overhead dwarfs it:

The plain loop wins by a wide margin. The process pool with default settings sends 100,000 individual messages. Setting chunksize batches them and recovers most of that time, but we could still use the plain loop here.

plain loop          0.00s
processes           6.09s
chunksize=5000      0.02s

Rule of thumb: if a single task takes less than a few milliseconds, group tasks into chunks before handing them to a process.

Threads for CPU work. We already watched this fail. More threads, same wall-clock time, extra complexity.

Threads with shared mutable state. Threads share memory, which is the point and also the problem. Two threads updating the same dictionary or counter need a lock. We will see a nasty example of this in Part II, because free-threaded Python turns this from “rare” into “real”.

Unbounded pools. Using something like max_workers=500 for requests is not ambition, it is a denial-of-service attack with extra steps. Most sites will rate-limit you, and some will ban you. A polite-bouncer decorator pairs well with any pool.


Recap

Task type

Tool

Why

Waiting on I/O

ThreadPoolExecutor

Waiting releases the GIL

Computing in Python

ProcessPoolExecutor

One GIL per process

Both

One pool of each

Give every stage what it needs

The GIL is a rule about computation. Treating it as a bug or a wall misses that distinction, which explains the “except when it can, except when it can’t” confusion.

That covers two of the four ways. The next uses one thread and a lot of politeness, without adding threads or processes.

Comments


bottom of page