44Multi-threaded programming
55**************************
66
7- A :term: `thread ` is an independent flow of execution inside a program. Every
7+ A :term: `thread ` is an independent flow of execution inside a program. Every
88Python program has at least one thread, the *main thread *, and a program
9- that never starts another is *single-threaded *. A *multi-threaded * program
9+ that 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
12+ :class: `concurrent.futures.ThreadPoolExecutor `. Each thread runs its own
1313function :term: `concurrently <concurrency> ` with the others.
1414
1515Using threads allows a program's execution to proceed when it is necessary to
@@ -22,38 +22,39 @@ examples of blocking calls. :mod:`asyncio` does the same job for code written
2222with ``async `` and ``await ``; threads do it for ordinary functions that may
2323block.
2424
25- Threads can also divide work between CPU cores. In the default build of
25+ Threads can also divide work between CPU cores. In the default build of
2626CPython, :term: `parallelism ` between threads is only possible while an
2727operation releases the :term: `global interpreter lock ` (GIL), as blocking I/O
28- and many functions implemented in :term: `native code ` do. In the
28+ and many functions implemented in :term: `native code ` do. In the
2929:term: `free-threaded build ` the GIL is disabled, and threads can also run
3030Python code in parallel, assuming some other lock or coordination does not
3131hinder parallelism.
3232
3333All the threads in a program share the same modules and globals. Objects can
3434also be shared between threads, allowing multiple threads to simultaneously
35- access the the same data directly. This can avoid the costs that
35+ access the same data directly. Sharing objects can avoid the costs that
3636:mod: `multiprocessing ` pays to start processes and to copy data between
3737processes.
3838
3939Sharing objects between threads also introduces the possibility of bugs that
40- cannot occur in single-threaded programs. An :mod: `asyncio ` task only
40+ cannot occur in single-threaded programs. An :mod: `asyncio ` task only
4141gives up control at an ``await ``, but a thread can be interrupted at any point
4242so that another can run, and two threads can even be using the same objects at
43- the same instant. Code that is correct when one thread runs it can therefore
43+ the same instant. Code that is correct when one thread runs it can therefore
4444give wrong answers when several threads run it, and it may only do so
45- occasionally. Such a bug is called a :term: `race condition `.
45+ occasionally. Such a bug is called a :term: `race condition `.
4646
4747Code that behaves correctly when several threads use it concurrently is called
48- thread-safe. The rest of the guide explains how to recognize code that is not
49- thread-safe and how to fix it. After reading the guide , you should be able to
50- answer these questions:
48+ :term: ` thread-safe ` . The rest of this HOWTO explains how to recognize code
49+ that is not thread-safe and how to fix it. After reading this HOWTO , you
50+ should be able to answer these questions:
5151
5252- Should my program use threads or a different form of concurrency?
5353- Why does my threaded program give different results from run to run and how
5454 do I make my program deterministic?
5555- Which objects can my program safely share between threads?
56- - What are my options for protecting shared data, and what does each option cost?
56+ - What are my options for protecting shared data, and what does each option
57+ cost?
5758- How do I coordinate work between the threads in my program?
5859
5960This HOWTO describes several strategies for making code thread-safe. Working
@@ -66,14 +67,14 @@ multiple threads.
6667.. TODO: adjust the list of questions to match the sections once they are
6768 written.
6869
69- .. TODO: link glossary entries on first use. Beyond the ones linked above,
70+ .. TODO: link glossary entries on first use. Beyond the ones linked above,
7071 the glossary has: atomic operation, concurrent modification, data race,
7172 deadlock, global interpreter lock, global state, immutable, lock-free,
7273 mutable, per-object lock, reentrant, synchronization primitive.
7374
7475 The advice applies both to the default build of CPython and to the
75- :term: `free-threaded build `. Places where the two builds
76- behave differently are called out where they matter .
76+ :term: `free-threaded build `. Places where the two builds
77+ behave differently are marked with a box titled "Free-threaded build" .
7778
7879.. seealso ::
7980
@@ -85,17 +86,24 @@ behave differently are called out where they matter.
8586 from several threads.
8687
8788 :mod: `threading `, :mod: `queue ` and :mod: `concurrent.futures `
88- The reference documentation for the modules used in this guide .
89+ The reference documentation for the modules used in this HOWTO .
8990
90- .. TODO: decide on one callout style for build differences (for example a
91- note that starts "On the free-threaded build") and use it throughout.
91+ .. TODO: every "Build difference" item in the notes below becomes a titled
92+ admonition, placed where the difference matters. Use the same title
93+ every time and describe both builds inside the box when the difference
94+ is about the default build:
95+
96+ .. admonition:: Free-threaded build
97+
98+ Concurrent calls to ``next()`` on one iterator can skip or
99+ duplicate items.
92100
93101
94102 Is threading the right tool?
95103============================
96104
97105.. TODO: keep this to a paragraph or two.
98- - Who this guide is for.
106+ - Who this HOWTO is for.
99107 - Short comparison with asyncio, multiprocessing and
100108 concurrent.interpreters, with links rather than detail.
101109 - asyncio and threads both keep a program going while something waits.
@@ -106,30 +114,30 @@ Is threading the right tool?
106114 only at an await, while a thread can be preempted anywhere and
107115 threads can run simultaneously on the same objects.
108116 - Compared with multiprocessing, threads avoid the cost of starting
109- processes and of copying data between them. Do not describe sharing
117+ processes and of copying data between them. Do not describe sharing
110118 as free: see the note on contention under "Fine-grained locks".
111119 - Build difference: under the GIL, threads run in parallel only while an
112120 operation releases the GIL, which blocking I/O and much native code
113- do. On the free-threaded build, Python code runs in parallel too.
121+ do. On the free-threaded build, Python code runs in parallel too.
114122
115123
116124 What goes wrong
117125===============
118126
119127.. TODO:
120- - Motivating example: a counter. Show the serial version giving a
128+ - Motivating example: a counter. Show the serial version giving a
121129 consistent result, then an unsynchronized threaded version giving
122130 results that vary from run to run.
123- - The example has to fail on both builds. A bare ``counter += 1`` loop
131+ - The example has to fail on both builds. A bare ``counter += 1`` loop
124132 almost never loses updates under the GIL since 3.10, because thread
125- switches only happen at backward jumps and calls. Use a check-then-act
133+ switches only happen at backward jumps and calls. Use a check-then-act
126134 with a call in the middle, or use the difference to show that the GIL
127135 hides races without removing them.
128136 - Define "data race" and "race condition" and keep them distinct.
129137 Link the glossary entries for both, and for "atomic operation".
130138 - Compound operations: check-then-act and read-modify-write.
131139 - What built-in types guarantee: single operations are safe, sequences of
132- them are not. Link to the thread safety reference.
140+ them are not. Link to the thread safety reference.
133141 - Wording: reserve "guarantee" for documented behaviour on both builds.
134142 Anything else that happens to hold under the GIL is not to be relied on.
135143
@@ -152,7 +160,7 @@ Strategies for sharing data
152160===========================
153161
154162The strategies below are ordered from the one to reach for first to the one
155- to reach for last. Each fixes the same running example, a global dictionary
163+ to reach for last. Each fixes the same running example, a global dictionary
156164used as a cache, so that the costs can be compared.
157165
158166.. TODO: introduce the running example: a module-level dict cache filled by
@@ -215,11 +223,11 @@ Don't share
215223-----------
216224
217225.. TODO:
218- - What matters is shared mutation. Work that is partitioned so that no
226+ - What matters is shared mutation. Work that is partitioned so that no
219227 two threads touch the same data is safe by construction.
220228 - Example: filling an image where each thread fills a disjoint band.
221229 Standard library only (bytearray or list), using executor.map().
222- - Per-thread results merged at the end. This also fixes the counter.
230+ - Per-thread results merged at the end. This also fixes the counter.
223231 - threading.local and contextvars for per-thread state; when to prefer
224232 which.
225233 - Cost: the work has to be restructured, and per-thread copies of a cache
@@ -229,7 +237,7 @@ Don't share
229237 build.
230238 - Build difference: the partitioned example is safe on both builds.
231239 Under the GIL it is only faster if the work on each piece releases the
232- GIL. On the free-threaded build, pure-Python work speeds up too.
240+ GIL. On the free-threaded build, pure-Python work speeds up too.
233241
234242
235243 .. _multi-threading-immutable :
@@ -261,11 +269,11 @@ Copy-on-write
261269
262270.. TODO:
263271 - Define on first use: never mutate the shared object; copy it, modify the
264- copy, then rebind the shared reference. Distinguish from the lazy-copy
272+ copy, then rebind the shared reference. Distinguish from the lazy-copy
265273 optimization of the same name (fork, pandas).
266274 - Readers take one snapshot of the shared reference and use only that.
267275 - Without a writer lock, the last writer wins and concurrent updates are
268- lost. That is fine for memoization and wrong for most other state.
276+ lost. That is fine for memoization and wrong for most other state.
269277 Adding a lock around writers fixes it and keeps readers lock-free.
270278 - Cost: each write copies the whole structure.
271279
@@ -293,7 +301,7 @@ Fine-grained locks
293301 - Cost: more locks mean more ways to deadlock and code that is harder to
294302 verify.
295303 - Removing locks does not guarantee scaling.
296- - Sharing is not free even without locks. Build difference: on the
304+ - Sharing is not free even without locks. Build difference: on the
297305 free-threaded build, threads that use the same objects contend on
298306 their reference counts, which limits scaling.
299307
0 commit comments