From 7bc305d6f56161d02fec6635d022480c10065915 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 23 Nov 2026 10:23:29 -0700 Subject: [PATCH 1/5] Add a glossary entry for "thread" --- Doc/glossary.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Doc/glossary.rst b/Doc/glossary.rst index f0934dc2e138771..cacdd388a2ccc04 100644 --- a/Doc/glossary.rst +++ b/Doc/glossary.rst @@ -1593,6 +1593,19 @@ Glossary See also :term:`binary file` for a file object able to read and write :term:`bytes-like objects `. + thread + An independent flow of execution within a process. 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 + :mod:`threading` module or indirectly through functionality provided + by a library, such as :class:`concurrent.futures.ThreadPoolExecutor`. + All threads in a process share the same memory, so they can access + the same objects. + + See also :term:`concurrency`, :term:`parallelism` and + :term:`thread-safe`. + thread state The information used by the :term:`CPython` runtime to run in an OS thread. From 0e71759a44a4e77d2889a5eb99ec3ff282c0dba5 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 23 Nov 2026 10:23:29 -0700 Subject: [PATCH 2/5] Add an outline for a multi-threaded programming HOWTO --- Doc/howto/index.rst | 2 + Doc/howto/multi-threading.rst | 296 ++++++++++++++++++++++++++++++++++ 2 files changed, 298 insertions(+) create mode 100644 Doc/howto/multi-threading.rst diff --git a/Doc/howto/index.rst b/Doc/howto/index.rst index 57e2d6e0752447f..8edce4c88dfff85 100644 --- a/Doc/howto/index.rst +++ b/Doc/howto/index.rst @@ -22,6 +22,7 @@ Python Library Reference. functional.rst logging.rst logging-cookbook.rst + multi-threading.rst regex.rst sockets.rst sorting.rst @@ -51,6 +52,7 @@ General: * :ref:`ipaddress-howto` * :ref:`logging-howto` * :ref:`logging-cookbook` +* :ref:`multi-threading-howto` * :ref:`regex-howto` * :ref:`sortinghowto` * :ref:`unicode-howto` diff --git a/Doc/howto/multi-threading.rst b/Doc/howto/multi-threading.rst new file mode 100644 index 000000000000000..3800695d729cda0 --- /dev/null +++ b/Doc/howto/multi-threading.rst @@ -0,0 +1,296 @@ +.. _multi-threading-howto: + +************************** +Multi-threaded programming +************************** + +A :term:`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 :mod:`threading` module or +indirectly through functionality provided by a library, such as +:class:`concurrent.futures.ThreadPoolExecutor`. Each thread runs its own +function :term:`concurrently ` with the others. + +Threads are useful in two ways. One thread can wait on a blocking call, such +as reading a file or querying a database, while the others keep working. +:mod:`asyncio` does the same job for code written with ``async`` and +``await``; threads do it for ordinary blocking functions. + +Threads can also divide work between CPU cores. In the default build of +CPython, :term:`parallelism` between threads is only possible while an +operation releases the :term:`global interpreter lock` (GIL), as blocking I/O +and many functions implemented in :term:`native code` do. In the +:term:`free-threaded build` the GIL is disabled, and threads can also run +Python code in parallel. + +All the threads in a program share the same modules, globals and objects. +Threads can work on the same data directly, which avoids the costs that +:mod:`multiprocessing` pays to start processes and to copy data between +them. + +Sharing is also where the bugs come from. An :mod:`asyncio` task only gives +up control 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 when one thread runs it can therefore +give wrong answers when several threads run it, and it may only do so +occasionally. Such a bug is called a :term:`race condition`. + +This guide is about writing :term:`thread-safe` code, which stays correct in +that situation. After reading it you should be able to answer these +questions: + +- Should this program use threads at all? +- Why does my threaded program give different results from run to run? +- Which operations on lists and dicts are safe to use from several threads? +- When is a :term:`lock` the right fix, and what does it cost? +- How do I share a cache between threads without locking every read? + +Every strategy described here is a trade-off between safety, performance and +how simple the code stays. Each section describes what a strategy costs as +well as what it buys. + +.. TODO: adjust the list of questions to match the sections once they are + written. + +.. TODO: link glossary entries on first use. Beyond the ones linked above, + the glossary has: atomic operation, concurrent modification, data race, + deadlock, global interpreter lock, global state, immutable, lock-free, + mutable, per-object lock, reentrant, synchronization primitive. + +The advice applies both to the default build of CPython and to the +:term:`free-threaded build`. Places where the two builds +behave differently are called out where they matter. + +.. seealso:: + + :ref:`freethreading-python-howto` + Describes the free-threaded build itself. + + :ref:`threadsafety` + The reference for which operations on built-in types are safe to use + from several threads. + + :mod:`threading`, :mod:`queue` and :mod:`concurrent.futures` + The reference documentation for the modules used in this guide. + +.. TODO: decide on one callout style for build differences (for example a + note that starts "On the free-threaded build") and use it throughout. + + +Is threading the right tool? +============================ + +.. TODO: keep this to a paragraph or two. + - Who this guide is for. + - Short comparison with asyncio, multiprocessing and + concurrent.interpreters, with links rather than detail. + - asyncio and threads both keep a program going while something waits. + asyncio needs code written with async and await; threads work with + ordinary blocking functions, and asyncio itself uses threads for + those (asyncio.to_thread(), loop.run_in_executor()). + - The price of not needing async and await: an asyncio task switches + only at an await, while a thread can be preempted anywhere and + threads can run simultaneously on the same objects. + - Compared with multiprocessing, threads avoid the cost of starting + processes and of copying data between them. Do not describe sharing + as free: see the note on contention under "Fine-grained locks". + - Build difference: under the GIL, threads run in parallel only while an + operation releases the GIL, which blocking I/O and much native code + do. On the free-threaded build, Python code runs in parallel too. + + +What goes wrong +=============== + +.. TODO: + - Motivating example: a counter. Show the serial version giving a + consistent result, then an unsynchronized threaded version giving + results that vary from run to run. + - The example has to fail on both builds. A bare ``counter += 1`` loop + almost never loses updates under the GIL since 3.10, because thread + switches only happen at backward jumps and calls. Use a check-then-act + with a call in the middle, or use the difference to show that the GIL + hides races without removing them. + - Define "data race" and "race condition" and keep them distinct. + Link the glossary entries for both, and for "atomic operation". + - Compound operations: check-then-act and read-modify-write. + - What built-in types guarantee: single operations are safe, sequences of + them are not. Link to the thread safety reference. + - Wording: reserve "guarantee" for documented behaviour on both builds. + Anything else that happens to hold under the GIL is not to be relied on. + + +Running threads +=============== + +.. TODO: keep this short; the threading and concurrent.futures references + cover the API. + - concurrent.futures.ThreadPoolExecutor first, threading.Thread second. + - Waiting for threads: join() and futures. + - Exceptions: threading.excepthook compared with exceptions carried by + futures. + - Stopping a thread: there is no way to kill one, so cancellation is + cooperative (threading.Event). + - Daemon threads and interpreter shutdown. + + +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. + +.. TODO: introduce the running example: a module-level dict cache filled by + an expensive function, called from several threads. + +.. TODO: every rating in this table is a placeholder judgment and needs + review. + +.. list-table:: Trade-offs between the strategies + :header-rows: 1 + :widths: 18 11 11 11 11 38 + + * - Strategy + - Hard to get wrong + - Scales when reads dominate + - Scales when writes dominate + - Simple code + - Main cost + * - :ref:`Don't share ` + - High + - High + - High + - Medium + - The work has to partition cleanly + * - :ref:`Share immutable objects ` + - High + - High + - Low + - Medium + - Every update makes a copy + * - :ref:`Hand off ownership ` + - Medium + - Medium + - Medium + - Medium + - Queue overhead; the program becomes a pipeline + * - :ref:`Copy-on-write ` + - Medium + - High + - Low + - Low + - Copies on every write; updates can be lost without a writer lock + * - :ref:`One coarse lock ` + - Medium + - Low + - Low + - High + - Threads take turns + * - :ref:`Fine-grained locks ` + - Low + - High + - Medium + - Low + - Deadlock risk; hard to verify + + +.. _multi-threading-dont-share: + +Don't share +----------- + +.. TODO: + - What matters is shared mutation. Work that is partitioned so that no + two threads touch the same data is safe by construction. + - Example: filling an image where each thread fills a disjoint band. + Standard library only (bytearray or list), using executor.map(). + - Per-thread results merged at the end. This also fixes the counter. + - threading.local and contextvars for per-thread state; when to prefer + which. + - Cost: the work has to be restructured, and per-thread copies of a cache + multiply memory use and repeat work. + - Build difference: sys.flags.thread_inherit_context defaults differ, so + whether a new thread sees the caller's context variables depends on the + build. + - Build difference: the partitioned example is safe on both builds. + Under the GIL it is only faster if the work on each piece releases the + GIL. On the free-threaded build, pure-Python work speeds up too. + + +.. _multi-threading-immutable: + +Share immutable objects +----------------------- + +.. TODO: + - tuple, frozenset, frozendict, frozen dataclasses. + - Immutability is shallow: a tuple of lists is still shared mutable state. + - Cost: every update builds a new object. + + +.. _multi-threading-handoff: + +Hand off ownership +------------------ + +.. TODO: + - Only one thread owns an object at a time; queue.Queue transfers it. + - Producer-consumer example, including Queue.shutdown(). + - Cost: queue overhead, and the program has to be shaped as a pipeline. + + +.. _multi-threading-copy-on-write: + +Copy-on-write +------------- + +.. TODO: + - Define on first use: never mutate the shared object; copy it, modify the + copy, then rebind the shared reference. Distinguish from the lazy-copy + optimization of the same name (fork, pandas). + - Readers take one snapshot of the shared reference and use only that. + - Without a writer lock, the last writer wins and concurrent updates are + lost. That is fine for memoization and wrong for most other state. + Adding a lock around writers fixes it and keeps readers lock-free. + - Cost: each write copies the whole structure. + + +.. _multi-threading-coarse-lock: + +One coarse lock +--------------- + +.. TODO: + - threading.Lock around every access, with the "with" statement. + - A lock only protects data if every access takes it. + - Checking again after acquiring the lock; one-time initialization. + - Cost: threads take turns, so there is no parallel speedup inside the + lock. + + +.. _multi-threading-fine-grained-locks: + +Fine-grained locks +------------------ + +.. TODO: + - One lock per object or per shard of the data. + - Cost: more locks mean more ways to deadlock and code that is harder to + verify. + - Removing locks does not guarantee scaling. + - Sharing is not free even without locks. Build difference: on the + free-threaded build, threads that use the same objects contend on + their reference counts, which limits scaling. + + +Coordinating threads +==================== + +.. TODO: a table from the need to the primitive, with little or no prose: + - wait until something has happened: threading.Event + - wait until a condition on shared state holds: threading.Condition + - limit how many threads do something at once: threading.Semaphore + - start several threads at the same moment: threading.Barrier + - pass work between threads: queue.Queue From 6adf1823ce000803940e456185b4812478426899 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 23 Nov 2026 10:58:01 -0700 Subject: [PATCH 3/5] Intro edits --- Doc/howto/multi-threading.rst | 61 +++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/Doc/howto/multi-threading.rst b/Doc/howto/multi-threading.rst index 3800695d729cda0..522ec83a6d0b306 100644 --- a/Doc/howto/multi-threading.rst +++ b/Doc/howto/multi-threading.rst @@ -12,43 +12,56 @@ indirectly through functionality provided by a library, such as :class:`concurrent.futures.ThreadPoolExecutor`. Each thread runs its own function :term:`concurrently ` with the others. -Threads are useful in two ways. One thread can wait on a blocking call, such -as reading a file or querying a database, while the others keep working. -:mod:`asyncio` does the same job for code written with ``async`` and -``await``; threads do it for ordinary blocking functions. +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. :mod:`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, :term:`parallelism` between threads is only possible while an operation releases the :term:`global interpreter lock` (GIL), as blocking I/O and many functions implemented in :term:`native code` do. In the :term:`free-threaded build` the GIL is disabled, and threads can also run -Python code in parallel. +Python code in parallel, assuming some other lock or coordination does not +hinder parallelism. -All the threads in a program share the same modules, globals and objects. -Threads can work on the same data directly, which avoids the costs that +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 the same data directly. This can avoid the costs that :mod:`multiprocessing` pays to start processes and to copy data between -them. +processes. -Sharing is also where the bugs come from. An :mod:`asyncio` task only gives -up control 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 +Sharing objects between threads also introduces the possibility of bugs that +cannot occur in single-threaded programs. An :mod:`asyncio` task only +gives up control 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 when one thread runs it can therefore give wrong answers when several threads run it, and it may only do so occasionally. Such a bug is called a :term:`race condition`. -This guide is about writing :term:`thread-safe` code, which stays correct in -that situation. After reading it you should be able to answer these -questions: - -- Should this program use threads at all? -- Why does my threaded program give different results from run to run? -- Which operations on lists and dicts are safe to use from several threads? -- When is a :term:`lock` the right fix, and what does it cost? -- How do I share a cache between threads without locking every read? - -Every strategy described here is a trade-off between safety, performance and -how simple the code stays. Each section describes what a strategy costs as -well as what it buys. +Code that behaves correctly when several threads use it concurrently is called +thread-safe. The rest of the guide explains how to recognize code that is not +thread-safe and how to fix it. After reading the guide, 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 describes several strategies for making 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. .. TODO: adjust the list of questions to match the sections once they are written. From 6703ccc997d762bc6be7b215d8f6a65624cefc62 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 23 Nov 2026 11:02:45 -0700 Subject: [PATCH 4/5] add free-threading admonition and use single-spaces --- Doc/howto/multi-threading.rst | 74 +++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 33 deletions(-) diff --git a/Doc/howto/multi-threading.rst b/Doc/howto/multi-threading.rst index 522ec83a6d0b306..e6238c571af06c8 100644 --- a/Doc/howto/multi-threading.rst +++ b/Doc/howto/multi-threading.rst @@ -4,12 +4,12 @@ Multi-threaded programming ************************** -A :term:`thread` is an independent flow of execution inside a program. Every +A :term:`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 +that never starts another is *single-threaded*. A *multi-threaded* program starts more threads, either directly with the :mod:`threading` module or indirectly through functionality provided by a library, such as -:class:`concurrent.futures.ThreadPoolExecutor`. Each thread runs its own +:class:`concurrent.futures.ThreadPoolExecutor`. Each thread runs its own function :term:`concurrently ` with the others. Using 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 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 +Threads can also divide work between CPU cores. In the default build of CPython, :term:`parallelism` between threads is only possible while an operation releases the :term:`global interpreter lock` (GIL), as blocking I/O -and many functions implemented in :term:`native code` do. In the +and many functions implemented in :term:`native code` do. In the :term:`free-threaded build` the GIL is disabled, and threads can also run Python code in parallel, assuming some other lock or coordination does not hinder parallelism. 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 the same data directly. This can avoid the costs that +access the same data directly. Sharing objects can avoid the costs that :mod:`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. An :mod:`asyncio` task only +cannot occur in single-threaded programs. An :mod:`asyncio` task only gives up control 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 when one thread runs it can therefore +the same instant. Code that is correct when one thread runs it can therefore give wrong answers when several threads run it, and it may only do so -occasionally. Such a bug is called a :term:`race condition`. +occasionally. Such a bug is called a :term:`race condition`. Code that behaves correctly when several threads use it concurrently is called -thread-safe. The rest of the guide explains how to recognize code that is not -thread-safe and how to fix it. After reading the guide, you should be able to -answer these questions: +:term:`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? +- 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 describes several strategies for making code thread-safe. Working @@ -66,14 +67,14 @@ multiple threads. .. TODO: adjust the list of questions to match the sections once they are written. -.. TODO: link glossary entries on first use. Beyond the ones linked above, +.. TODO: link glossary entries on first use. Beyond the ones linked above, the glossary has: atomic operation, concurrent modification, data race, deadlock, global interpreter lock, global state, immutable, lock-free, mutable, per-object lock, reentrant, synchronization primitive. The advice applies both to the default build of CPython and to the -:term:`free-threaded build`. Places where the two builds -behave differently are called out where they matter. +:term:`free-threaded build`. Places where the two builds +behave differently are marked with a box titled "Free-threaded build". .. seealso:: @@ -85,17 +86,24 @@ behave differently are called out where they matter. from several threads. :mod:`threading`, :mod:`queue` and :mod:`concurrent.futures` - The reference documentation for the modules used in this guide. + The reference documentation for the modules used in this HOWTO. -.. TODO: decide on one callout style for build differences (for example a - note that starts "On the free-threaded build") and use it throughout. +.. TODO: every "Build difference" item in the notes below becomes a titled + admonition, placed where the difference matters. Use the same title + every time and describe both builds inside the box when the difference + is about the default build: + + .. admonition:: Free-threaded build + + Concurrent calls to ``next()`` on one iterator can skip or + duplicate items. Is threading the right tool? ============================ .. TODO: keep this to a paragraph or two. - - Who this guide is for. + - Who this HOWTO is for. - Short comparison with asyncio, multiprocessing and concurrent.interpreters, with links rather than detail. - asyncio and threads both keep a program going while something waits. @@ -106,30 +114,30 @@ Is threading the right tool? only at an await, while a thread can be preempted anywhere and threads can run simultaneously on the same objects. - Compared with multiprocessing, threads avoid the cost of starting - processes and of copying data between them. Do not describe sharing + processes and of copying data between them. Do not describe sharing as free: see the note on contention under "Fine-grained locks". - Build difference: under the GIL, threads run in parallel only while an operation releases the GIL, which blocking I/O and much native code - do. On the free-threaded build, Python code runs in parallel too. + do. On the free-threaded build, Python code runs in parallel too. What goes wrong =============== .. TODO: - - Motivating example: a counter. Show the serial version giving a + - Motivating example: a counter. Show the serial version giving a consistent result, then an unsynchronized threaded version giving results that vary from run to run. - - The example has to fail on both builds. A bare ``counter += 1`` loop + - The example has to fail on both builds. A bare ``counter += 1`` loop almost never loses updates under the GIL since 3.10, because thread - switches only happen at backward jumps and calls. Use a check-then-act + switches only happen at backward jumps and calls. Use a check-then-act with a call in the middle, or use the difference to show that the GIL hides races without removing them. - Define "data race" and "race condition" and keep them distinct. Link the glossary entries for both, and for "atomic operation". - Compound operations: check-then-act and read-modify-write. - What built-in types guarantee: single operations are safe, sequences of - them are not. Link to the thread safety reference. + them are not. Link to the thread safety reference. - Wording: reserve "guarantee" for documented behaviour on both builds. Anything else that happens to hold under the GIL is not to be relied on. @@ -152,7 +160,7 @@ 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 +to reach for last. Each fixes the same running example, a global dictionary used as a cache, so that the costs can be compared. .. TODO: introduce the running example: a module-level dict cache filled by @@ -215,11 +223,11 @@ Don't share ----------- .. TODO: - - What matters is shared mutation. Work that is partitioned so that no + - What matters is shared mutation. Work that is partitioned so that no two threads touch the same data is safe by construction. - Example: filling an image where each thread fills a disjoint band. Standard library only (bytearray or list), using executor.map(). - - Per-thread results merged at the end. This also fixes the counter. + - Per-thread results merged at the end. This also fixes the counter. - threading.local and contextvars for per-thread state; when to prefer which. - Cost: the work has to be restructured, and per-thread copies of a cache @@ -229,7 +237,7 @@ Don't share build. - Build difference: the partitioned example is safe on both builds. Under the GIL it is only faster if the work on each piece releases the - GIL. On the free-threaded build, pure-Python work speeds up too. + GIL. On the free-threaded build, pure-Python work speeds up too. .. _multi-threading-immutable: @@ -261,11 +269,11 @@ Copy-on-write .. TODO: - Define on first use: never mutate the shared object; copy it, modify the - copy, then rebind the shared reference. Distinguish from the lazy-copy + copy, then rebind the shared reference. Distinguish from the lazy-copy optimization of the same name (fork, pandas). - Readers take one snapshot of the shared reference and use only that. - Without a writer lock, the last writer wins and concurrent updates are - lost. That is fine for memoization and wrong for most other state. + lost. That is fine for memoization and wrong for most other state. Adding a lock around writers fixes it and keeps readers lock-free. - Cost: each write copies the whole structure. @@ -293,7 +301,7 @@ Fine-grained locks - Cost: more locks mean more ways to deadlock and code that is harder to verify. - Removing locks does not guarantee scaling. - - Sharing is not free even without locks. Build difference: on the + - Sharing is not free even without locks. Build difference: on the free-threaded build, threads that use the same objects contend on their reference counts, which limits scaling. From 049fd332c066352c4aacb710680573236da52352 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 23 Nov 2026 11:28:41 -0700 Subject: [PATCH 5/5] expand multithreaded guide --- Doc/howto/multi-threading.rst | 113 +++++++++++++++++----------------- 1 file changed, 58 insertions(+), 55 deletions(-) diff --git a/Doc/howto/multi-threading.rst b/Doc/howto/multi-threading.rst index e6238c571af06c8..2ac7bedd7cd7583 100644 --- a/Doc/howto/multi-threading.rst +++ b/Doc/howto/multi-threading.rst @@ -26,9 +26,8 @@ Threads can also divide work between CPU cores. In the default build of CPython, :term:`parallelism` between threads is only possible while an operation releases the :term:`global interpreter lock` (GIL), as blocking I/O and many functions implemented in :term:`native code` do. In the -:term:`free-threaded build` the GIL is disabled, and threads can also run -Python code in parallel, assuming some other lock or coordination does not -hinder parallelism. +:term:`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 @@ -37,17 +36,17 @@ access the same data directly. Sharing objects can avoid the costs that processes. Sharing objects between threads also introduces the possibility of bugs that -cannot occur in single-threaded programs. An :mod:`asyncio` task only -gives up control 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 when one thread runs it can therefore -give wrong answers when several threads run it, and it may only do so -occasionally. Such a bug is called a :term:`race condition`. - -Code that behaves correctly when several threads use it concurrently is called -:term:`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: +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 :term:`race condition`. + +APIs that behave correctly when several threads use functions, objects, and +types provided the API concurrently are called :term:`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 @@ -57,15 +56,16 @@ should be able to answer these questions: cost? - How do I coordinate work between the threads in my program? -This HOWTO describes several strategies for making 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. +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. -.. TODO: adjust the list of questions to match the sections once they are - written. +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. .. TODO: link glossary entries on first use. Beyond the ones linked above, the glossary has: atomic operation, concurrent modification, data race, @@ -99,30 +99,8 @@ behave differently are marked with a box titled "Free-threaded build". duplicate items. -Is threading the right tool? -============================ - -.. TODO: keep this to a paragraph or two. - - Who this HOWTO is for. - - Short comparison with asyncio, multiprocessing and - concurrent.interpreters, with links rather than detail. - - asyncio and threads both keep a program going while something waits. - asyncio needs code written with async and await; threads work with - ordinary blocking functions, and asyncio itself uses threads for - those (asyncio.to_thread(), loop.run_in_executor()). - - The price of not needing async and await: an asyncio task switches - only at an await, while a thread can be preempted anywhere and - threads can run simultaneously on the same objects. - - Compared with multiprocessing, threads avoid the cost of starting - processes and of copying data between them. Do not describe sharing - as free: see the note on contention under "Fine-grained locks". - - Build difference: under the GIL, threads run in parallel only while an - operation releases the GIL, which blocking I/O and much native code - do. On the free-threaded build, Python code runs in parallel too. - - -What goes wrong -=============== +Understanding Race Conditions +============================= .. TODO: - Motivating example: a counter. Show the serial version giving a @@ -145,15 +123,40 @@ What goes wrong Running threads =============== -.. TODO: keep this short; the threading and concurrent.futures references - cover the API. - - concurrent.futures.ThreadPoolExecutor first, threading.Thread second. - - Waiting for threads: join() and futures. - - Exceptions: threading.excepthook compared with exceptions carried by - futures. - - Stopping a thread: there is no way to kill one, so cancellation is - cooperative (threading.Event). - - Daemon threads and interpreter shutdown. +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. + +.. list-table:: + :header-rows: 1 + :widths: 40 60 + + * - Task you want to perform + - The best tool for the task + * - Run a function in another thread and use its return value + - :meth:`ThreadPoolExecutor.submit() `, + which returns a :class:`~concurrent.futures.Future` + * - Run a function once for each item in a collection + - :meth:`ThreadPoolExecutor.map() ` + * - Run a function in a thread with low-level control over the thread + - :class:`threading.Thread` + * - Call a blocking function from :mod:`asyncio` code + - :func:`asyncio.to_thread` + * - Wait for threads to finish + - A :keyword:`with` block around a + :class:`~concurrent.futures.ThreadPoolExecutor`, or + :meth:`Thread.join() ` + * - Handle an exception raised in another thread + - Call :meth:`~concurrent.futures.Future.result` on the + :class:`~concurrent.futures.Future` that + :meth:`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 +:class:`threading.Event` and return when the event is set. Strategies for sharing data