@@ -9,18 +9,21 @@ Python program has at least one thread, the *main thread*, and a program
99that never starts another is *single-threaded *. A *multi-threaded * program
1010starts more threads, either directly with the :mod: `threading ` module or
1111indirectly through functionality provided by a library, such as
12- :class: `concurrent.futures.ThreadPoolExecutor `. Each thread runs its own
13- function :term: `concurrently <concurrency> ` with the others.
12+ :class: `concurrent.futures.ThreadPoolExecutor `. Each thread works
13+ :term: `concurrently <concurrency> ` with the others.
1414
1515Using threads allows a program's execution to proceed when it is necessary to
1616do work that might take a long time to complete or might never complete. For
1717example, a GUI application must remain responsive to user input and must not
18- appear to freeze because it is doing other work and cannot check for user
19- input. When a function makes its caller wait for an arbitrarily long time, it
20- is called a *blocking call *. Reading a file and querying a database are
21- examples of blocking calls. :mod: `asyncio ` does the same job for code written
22- with ``async `` and ``await ``; threads do it for ordinary functions that may
23- block.
18+ appear to freeze while it does other work. When a function makes its caller
19+ wait for an arbitrarily long time, it is called a *blocking call *. Reading a
20+ file and querying a database are examples of blocking calls. :mod: `asyncio `
21+ does the same job for code written with ``async `` and ``await ``; threads do it
22+ for ordinary functions that may block.
23+
24+
25+ Threads and parallelism
26+ =======================
2427
2528Threads can also divide work between CPU cores. In the default build of
2629CPython, :term: `parallelism ` between threads is only possible while an
@@ -29,6 +32,10 @@ and many functions implemented in :term:`native code` do. In the
2932:term: `free-threaded build `, there is no GIL and threads can run
3033Python code in parallel.
3134
35+
36+ Sharing objects between threads
37+ ===============================
38+
3239All the threads in a program share the same modules and globals. Objects can
3340also be shared between threads, allowing multiple threads to simultaneously
3441access the same data directly. Sharing objects can avoid the costs that
@@ -43,10 +50,20 @@ same instant. Code that is correct in single-threaded use can therefore give
4350wrong answers in multi-threaded use, and it may only do so occasionally. Such a
4451bug is called a :term: `race condition `.
4552
53+
54+ Thread safety
55+ =============
56+
4657APIs that behave correctly when several threads use functions, objects, and
4758types provided the API concurrently are called :term: `thread-safe `. The rest of
4859this HOWTO explains how to recognize code that is not thread-safe and how to fix
49- it. After reading this HOWTO, you should be able to answer these questions:
60+ it.
61+
62+
63+ What this HOWTO covers
64+ ======================
65+
66+ After reading this HOWTO, you should be able to answer these questions:
5067
5168- Should my program use threads or a different form of concurrency?
5269- Why does my threaded program give different results from run to run and how
@@ -63,14 +80,18 @@ classes, and it does not assume any experience with threads.
6380Below, we describe several strategies for making Python code
6481thread-safe. Working with threads requires a trade-off between safety,
6582performance and code simplicity. Each section describes the costs of a strategy
66- as well as its benefits. Hopefully you can use the examples below to write and
83+ as well as its benefits, and the :ref: `table of trade-offs
84+ <multi-threading-trade-offs>` compares the strategies on safety, performance
85+ and code simplicity. Hopefully you can use the examples below to write and
6786update real-world Python code to use threads or fix issues seen when executing
6887in multiple threads.
6988
7089.. TODO: link glossary entries on first use. Beyond the ones linked above,
7190 the glossary has: atomic operation, concurrent modification, data race,
7291 deadlock, global interpreter lock, global state, immutable, lock-free,
7392 mutable, per-object lock, reentrant, synchronization primitive.
93+ https://github.com/python/cpython/pull/162886 adds CPU-bound and
94+ I/O-bound. Link those two terms once that PR is merged.
7495
7596 The advice applies both to the default build of CPython and to the
7697:term: `free-threaded build `. Places where the two builds
@@ -99,7 +120,47 @@ behave differently are marked with a box titled "Free-threaded build".
99120 duplicate items.
100121
101122
102- Understanding Race Conditions
123+ Should I use threads at all?
124+ ============================
125+
126+ .. TODO: keep this to a few paragraphs, with links rather than detail.
127+ - Two questions decide which form of concurrency to use. What does the
128+ program do: wait on many connections, call blocking functions, or
129+ compute? Does the work share data?
130+ - asyncio or threads? Prefer asyncio for a program that mostly waits on
131+ many network connections, that needs cancellation and timeouts, or
132+ whose libraries are async. Prefer threads when the program or its
133+ libraries use ordinary blocking functions, or when the work is
134+ CPU-bound. Link to "asyncio and free-threaded Python"
135+ (library/asyncio-threading.rst) for combining asyncio with threads.
136+ - In an asyncio program, using threads means asyncio.to_thread() or
137+ loop.run_in_executor(). A blocking call stalls the event loop even if
138+ it releases the GIL, because the loop runs every task on one thread.
139+ - Threads or multiprocessing and concurrent.interpreters? CPU-bound
140+ Python code is the only case where the default build and the
141+ free-threaded build call for different tools. Refer back to "Threads
142+ and parallelism" for why.
143+ - multiprocessing and concurrent.interpreters: prefer them when the work
144+ shares little data, or needs isolation from crashes or from code that
145+ is not thread-safe. The cost is starting workers and copying data
146+ between them.
147+ - No concurrency: a single-threaded program that is fast enough is the
148+ easiest to get right. Measure before adding threads.
149+ - Sharing implies synchronization, and synchronization has a cost even
150+ when the program takes no locks of its own. On the default build the
151+ GIL synchronizes: only one thread runs Python code at a time. On the
152+ free-threaded build the interpreter synchronizes per object (reference
153+ counts, per-object locks), so threads that use the same objects slow
154+ each other down. Weigh the cost of synchronization against the cost of
155+ copying data between processes or interpreters.
156+ - Do not name QSBR or other interpreter internals here.
157+ - https://github.com/python/cpython/pull/162888 adds a table of which
158+ form of concurrency to use to library/concurrency.rst, with the label
159+ concurrency-choosing. Once that PR is merged, link to the table from
160+ this section and cut from this section whatever the table already says.
161+
162+
163+ Understanding race conditions
103164=============================
104165
105166.. TODO:
@@ -172,6 +233,8 @@ used as a cache, so that the costs can be compared.
172233.. TODO: every rating in this table is a placeholder judgment and needs
173234 review.
174235
236+ .. _multi-threading-trade-offs :
237+
175238.. list-table :: Trade-offs between the strategies
176239 :header-rows: 1
177240 :widths: 18 11 11 11 11 38
@@ -200,12 +263,13 @@ used as a cache, so that the costs can be compared.
200263 - Medium
201264 - Medium
202265 - Queue overhead; the program becomes a pipeline
203- * - :ref: `Copy-on-write <multi-threading-copy-on-write >`
266+ * - :ref: `Rely on guarantees provided by built-ins
267+ <multi-threading-built-in-guarantees>`
204268 - Medium
205269 - High
206- - Low
207- - Low
208- - Copies on every write; updates can be lost without a writer lock
270+ - Medium
271+ - High
272+ - Only single operations are safe; copy-on-write copies on every write
209273 * - :ref: `One coarse lock <multi-threading-coarse-lock >`
210274 - Medium
211275 - Low
@@ -265,20 +329,32 @@ Hand off ownership
265329 - Cost: queue overhead, and the program has to be shaped as a pipeline.
266330
267331
268- .. _multi-threading-copy-on-write :
332+ .. _multi-threading-built-in-guarantees :
269333
270- Copy-on-write
271- -------------
334+ Rely on guarantees provided by built-ins
335+ ----------------------------------------
272336
273337.. TODO:
274- - Define on first use: never mutate the shared object; copy it, modify the
275- copy, then rebind the shared reference. Distinguish from the lazy-copy
338+ - A single operation on a built-in type needs no lock if the thread
339+ safety reference (the "threadsafety" label) documents it as safe. Fix
340+ the running example's cache with one call to dict.setdefault().
341+ - Only behaviour documented for both builds counts as a guarantee. Link
342+ to the thread safety reference instead of listing operations here.
343+ - A sequence of safe operations is not safe: refer back to compound
344+ operations in "Understanding race conditions".
345+ - Cost on the free-threaded build: the built-in types take per-object
346+ locks, so threads writing to one object take turns.
347+ - Copy-on-write relies on the guarantee for single operations, because
348+ reading a reference and rebinding a reference are each one operation.
349+ - Define copy-on-write on first use: never mutate the shared object; copy
350+ it, modify the copy, then rebind the shared reference. Distinguish from
351+ the lazy-copy
276352 optimization of the same name (fork, pandas).
277353 - Readers take one snapshot of the shared reference and use only that.
278354 - Without a writer lock, the last writer wins and concurrent updates are
279355 lost. That is fine for memoization and wrong for most other state.
280356 Adding a lock around writers fixes it and keeps readers lock-free.
281- - Cost: each write copies the whole structure.
357+ - Cost of copy-on-write : each write copies the whole structure.
282358
283359
284360 .. _multi-threading-coarse-lock :
@@ -290,6 +366,10 @@ One coarse lock
290366 - threading.Lock around every access, with the "with" statement.
291367 - A lock only protects data if every access takes it.
292368 - Checking again after acquiring the lock; one-time initialization.
369+ - threading.RLock: with one lock, a function that holds it and calls
370+ another function that takes it blocks forever. RLock lets the thread
371+ that holds the lock acquire it again. Leave what RLock hides to the
372+ "Locking hazards" section planned for a later PR.
293373 - Cost: threads take turns, so there is no parallel speedup inside the
294374 lock.
295375
@@ -303,10 +383,9 @@ Fine-grained locks
303383 - One lock per object or per shard of the data.
304384 - Cost: more locks mean more ways to deadlock and code that is harder to
305385 verify.
306- - Removing locks does not guarantee scaling.
307- - Sharing is not free even without locks. Build difference: on the
308- free-threaded build, threads that use the same objects contend on
309- their reference counts, which limits scaling.
386+ - Removing your own locks does not guarantee scaling, because the
387+ interpreter still synchronizes access to shared objects. Link to the
388+ synchronization cost bullet in "Should I use threads at all?".
310389
311390
312391 Coordinating threads
0 commit comments