Multi-threaded programming

A thread is an independent flow of execution inside a program. Every Python program has at least one thread, the main thread, and a program that never starts another is single-threaded. A multi-threaded program starts more threads, either directly with the threading module or indirectly through functionality provided by a library, such as concurrent.futures.ThreadPoolExecutor. Each thread runs its own function concurrently with the others.

Using threads allows a program’s execution to proceed when it is necessary to do work that might take a long time to complete or might never complete. For example, a GUI application must remain responsive to user input and must not appear to freeze because it is doing other work and cannot check for user input. When a function makes its caller wait for an arbitrarily long time, it is called a blocking call. Reading a file and querying a database are examples of blocking calls. asyncio does the same job for code written with async and await; threads do it for ordinary functions that may block.

Threads can also divide work between CPU cores. In the default build of CPython, parallelism between threads is only possible while an operation releases the global interpreter lock (GIL), as blocking I/O and many functions implemented in native code do. In the free-threaded build, there is no GIL and threads can run Python code in parallel.

All the threads in a program share the same modules and globals. Objects can also be shared between threads, allowing multiple threads to simultaneously access the same data directly. Sharing objects can avoid the costs that multiprocessing pays to start processes and to copy data between processes.

Sharing objects between threads also introduces the possibility of bugs that cannot occur in single-threaded programs. Tasks running on one asyncio event loop only switch at an await, but a thread can be interrupted at any point so that another can run, and two threads can even be using the same objects at the same instant. Code that is correct in single-threaded use can therefore give wrong answers in multi-threaded use, and it may only do so occasionally. Such a bug is called a race condition.

APIs that behave correctly when several threads use functions, objects, and types provided the API concurrently are called thread-safe. The rest of this HOWTO explains how to recognize code that is not thread-safe and how to fix it. After reading this HOWTO, you should be able to answer these questions:

  • Should my program use threads or a different form of concurrency?

  • Why does my threaded program give different results from run to run and how do I make my program deterministic?

  • Which objects can my program safely share between threads?

  • What are my options for protecting shared data, and what does each option cost?

  • How do I coordinate work between the threads in my program?

This HOWTO is for Python programmers who are new to writing multi-threaded code. It assumes you know Python’s built-in types and how to write functions and classes, and it does not assume any experience with threads.

Below, we describe several strategies for making Python code thread-safe. Working with threads requires a trade-off between safety, performance and code simplicity. Each section describes the costs of a strategy as well as its benefits. Hopefully you can use the examples below to write and update real-world Python code to use threads or fix issues seen when executing in multiple threads.

The advice applies both to the default build of CPython and to the free-threaded build. Places where the two builds behave differently are marked with a box titled “Free-threaded build”.

See also

Python support for free threading

Describes the free-threaded build itself.

Thread Safety Guarantees

The reference for which operations on built-in types are safe to use from several threads.

threading, queue and concurrent.futures

The reference documentation for the modules used in this HOWTO.

Understanding Race Conditions

Running threads

The standard library has several interfaces for running a code in another thread. The table below states, for each of a set of common tasks, the best tool to use for that task.

Task you want to perform

The best tool for the task

Run a function in another thread and use its return value

ThreadPoolExecutor.submit(), which returns a Future

Run a function once for each item in a collection

ThreadPoolExecutor.map()

Run a function in a thread with low-level control over the thread

threading.Thread

Call a blocking function from asyncio code

asyncio.to_thread()

Wait for threads to finish

A with block around a ThreadPoolExecutor, or Thread.join()

Handle an exception raised in another thread

Call result() on the Future that ThreadPoolExecutor.submit() returned.

Stopping a long-running thread is tricky. Python has no way to stop a thread from outside, and a thread stopped at an arbitrary point could leave a lock held or shared data half updated. Cancelling a thread therefore requires coordination, for example by having the thread periodically check a threading.Event and return when the event is set.

Strategies for sharing data

The strategies below are ordered from the one to reach for first to the one to reach for last. Each fixes the same running example, a global dictionary used as a cache, so that the costs can be compared.

Trade-offs between the strategies

Strategy

Hard to get wrong

Scales when reads dominate

Scales when writes dominate

Simple code

Main cost

Don’t share

High

High

High

Medium

The work has to partition cleanly

Share immutable objects

High

High

Low

Medium

Every update makes a copy

Hand off ownership

Medium

Medium

Medium

Medium

Queue overhead; the program becomes a pipeline

Copy-on-write

Medium

High

Low

Low

Copies on every write; updates can be lost without a writer lock

One coarse lock

Medium

Low

Low

High

Threads take turns

Fine-grained locks

Low

High

Medium

Low

Deadlock risk; hard to verify

Don’t share

Share immutable objects

Hand off ownership

Copy-on-write

One coarse lock

Fine-grained locks

Coordinating threads