@@ -26,9 +26,8 @@ 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
2828and many functions implemented in :term: `native code ` do. In the
29- :term: `free-threaded build ` the GIL is disabled, and threads can also run
30- Python code in parallel, assuming some other lock or coordination does not
31- hinder parallelism.
29+ :term: `free-threaded build `, there is no GIL and threads can run
30+ Python code in parallel.
3231
3332All the threads in a program share the same modules and globals. Objects can
3433also 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
3736processes.
3837
3938Sharing objects between threads also introduces the possibility of bugs that
40- cannot occur in single-threaded programs. An :mod: ` asyncio ` task only
41- gives up control at an `` await `` , but a thread can be interrupted at any point
42- so 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
44- give wrong answers when several threads run it , and it may only do so
45- occasionally. Such a bug is called a :term: `race condition `.
46-
47- Code that behaves correctly when several threads use it concurrently is called
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:
39+ cannot occur in single-threaded programs. Tasks running on one asyncio event
40+ loop only switch at an await, but a thread can be interrupted at any point so
41+ that another can run, and two threads can even be using the same objects at the
42+ same instant. Code that is correct in single-threaded use can therefore give
43+ wrong answers in multi-threaded use , and it may only do so occasionally. Such a
44+ bug is called a :term: `race condition `.
45+
46+ APIs that behave correctly when several threads use functions, objects, and
47+ types provided the API concurrently are called :term: `thread-safe `. The rest of
48+ this 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:
5150
5251- Should my program use threads or a different form of concurrency?
5352- 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:
5756 cost?
5857- How do I coordinate work between the threads in my program?
5958
60- This HOWTO describes several strategies for making code thread-safe. Working
61- with threads requires a trade-off between safety, performance and code
62- simplicity. Each section describes the costs of a strategy as well as its
63- benefits. Hopefully you can use the examples below to write and update
64- real-world Python code to use threads or fix issues seen when executing in
65- multiple threads.
59+ This HOWTO is for Python programmers who are new to writing multi-threaded
60+ code. It assumes you know Python's built-in types and how to write functions and
61+ classes, and it does not assume any experience with threads.
6662
67- .. TODO: adjust the list of questions to match the sections once they are
68- written.
63+ Below, we describe several strategies for making Python code
64+ thread-safe. Working with threads requires a trade-off between safety,
65+ performance 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
67+ update real-world Python code to use threads or fix issues seen when executing
68+ in multiple threads.
6969
7070.. TODO: link glossary entries on first use. Beyond the ones linked above,
7171 the glossary has: atomic operation, concurrent modification, data race,
@@ -99,30 +99,8 @@ behave differently are marked with a box titled "Free-threaded build".
9999 duplicate items.
100100
101101
102- Is threading the right tool?
103- ============================
104-
105- .. TODO: keep this to a paragraph or two.
106- - Who this HOWTO is for.
107- - Short comparison with asyncio, multiprocessing and
108- concurrent.interpreters, with links rather than detail.
109- - asyncio and threads both keep a program going while something waits.
110- asyncio needs code written with async and await; threads work with
111- ordinary blocking functions, and asyncio itself uses threads for
112- those (asyncio.to_thread(), loop.run_in_executor()).
113- - The price of not needing async and await: an asyncio task switches
114- only at an await, while a thread can be preempted anywhere and
115- threads can run simultaneously on the same objects.
116- - Compared with multiprocessing, threads avoid the cost of starting
117- processes and of copying data between them. Do not describe sharing
118- as free: see the note on contention under "Fine-grained locks".
119- - Build difference: under the GIL, threads run in parallel only while an
120- operation releases the GIL, which blocking I/O and much native code
121- do. On the free-threaded build, Python code runs in parallel too.
122-
123-
124- What goes wrong
125- ===============
102+ Understanding Race Conditions
103+ =============================
126104
127105.. TODO:
128106 - Motivating example: a counter. Show the serial version giving a
@@ -145,15 +123,40 @@ What goes wrong
145123 Running threads
146124===============
147125
148- .. TODO: keep this short; the threading and concurrent.futures references
149- cover the API.
150- - concurrent.futures.ThreadPoolExecutor first, threading.Thread second.
151- - Waiting for threads: join() and futures.
152- - Exceptions: threading.excepthook compared with exceptions carried by
153- futures.
154- - Stopping a thread: there is no way to kill one, so cancellation is
155- cooperative (threading.Event).
156- - Daemon threads and interpreter shutdown.
126+ The standard library has several interfaces for running a code in another
127+ thread. The table below states, for each of a set of common tasks, the best
128+ tool to use for that task.
129+
130+ .. list-table ::
131+ :header-rows: 1
132+ :widths: 40 60
133+
134+ * - Task you want to perform
135+ - The best tool for the task
136+ * - Run a function in another thread and use its return value
137+ - :meth: `ThreadPoolExecutor.submit() <concurrent.futures.Executor.submit> `,
138+ which returns a :class: `~concurrent.futures.Future `
139+ * - Run a function once for each item in a collection
140+ - :meth: `ThreadPoolExecutor.map() <concurrent.futures.Executor.map> `
141+ * - Run a function in a thread with low-level control over the thread
142+ - :class: `threading.Thread `
143+ * - Call a blocking function from :mod: `asyncio ` code
144+ - :func: `asyncio.to_thread `
145+ * - Wait for threads to finish
146+ - A :keyword: `with ` block around a
147+ :class: `~concurrent.futures.ThreadPoolExecutor `, or
148+ :meth: `Thread.join() <threading.Thread.join> `
149+ * - Handle an exception raised in another thread
150+ - Call :meth: `~concurrent.futures.Future.result ` on the
151+ :class: `~concurrent.futures.Future ` that
152+ :meth: `ThreadPoolExecutor.submit()
153+ <concurrent.futures.Executor.submit> ` returned.
154+
155+ Stopping a long-running thread is tricky. Python has no way to stop a thread
156+ from outside, and a thread stopped at an arbitrary point could leave a lock
157+ held or shared data half updated. Cancelling a thread therefore requires
158+ coordination, for example by having the thread periodically check a
159+ :class: `threading.Event ` and return when the event is set.
157160
158161
159162Strategies for sharing data
0 commit comments