Debian Codegraph @

Doc/library/_thread.rst

raw
1 :mod:`!_thread` --- Low-level threading API
2 ===========================================
3
4 .. module:: _thread
5 :synopsis: Low-level threading API.
6
7 .. index::
8 single: light-weight processes
9 single: processes, light-weight
10 single: binary semaphores
11 single: semaphores, binary
12
13 --------------
14
15 This module provides low-level primitives for working with multiple threads
16 (also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
17 control sharing their global data space. For synchronization, simple locks
18 (also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided.
19 The :mod:`threading` module provides an easier to use and higher-level
20 threading API built on top of this module.
21
22 .. index::
23 single: pthreads
24 pair: threads; POSIX
25
26 .. versionchanged:: 3.7
27 This module used to be optional, it is now always available.
28
29 This module defines the following constants and functions:
30
31 .. exception:: error
32
33 Raised on thread-specific errors.
34
35 .. versionchanged:: 3.3
36 This is now a synonym of the built-in :exc:`RuntimeError`.
37
38
39 .. function:: start_new_thread(function, args[, kwargs])
40
41 Start a new thread and return its identifier. The thread executes the
42 function *function* with the argument list *args* (which must be a tuple).
43 The optional *kwargs* argument specifies a dictionary of keyword arguments.
44
45 When the function returns, the thread silently exits.
46
47 When the function terminates with an unhandled exception,
48 :func:`sys.unraisablehook` is called to handle the exception. The *object*
49 attribute of the hook argument is *function*. By default, a stack trace is
50 printed and then the thread exits (but other threads continue to run).
51
52 When the function raises a :exc:`SystemExit` exception, it is silently
53 ignored.
54
55 .. audit-event:: _thread.start_new_thread function,args,kwargs start_new_thread
56
57 .. versionchanged:: 3.8
58 :func:`sys.unraisablehook` is now used to handle unhandled exceptions.
59
60
61 .. function:: interrupt_main(signum=signal.SIGINT, /)
62
63 Simulate the effect of a signal arriving in the main thread.
64 A thread can use this function to interrupt the main thread, though
65 there is no guarantee that the interruption will happen immediately.
66
67 If given, *signum* is the number of the signal to simulate.
68 If *signum* is not given, :const:`signal.SIGINT` is simulated.
69
70 If the given signal isn't handled by Python (it was set to
71 :const:`signal.SIG_DFL` or :const:`signal.SIG_IGN`), this function does
72 nothing.
73
74 .. versionchanged:: 3.10
75 The *signum* argument is added to customize the signal number.
76
77 .. note::
78 This does not emit the corresponding signal but schedules a call to
79 the associated handler (if it exists).
80 If you want to truly emit the signal, use :func:`signal.raise_signal`.
81
82
83 .. function:: exit()
84
85 Raise the :exc:`SystemExit` exception. When not caught, this will cause the
86 thread to exit silently.
87
88 ..
89 function:: exit_prog(status)
90
91 Exit all threads and report the value of the integer argument
92 *status* as the exit status of the entire program.
93 **Caveat:** code in pending :keyword:`finally` clauses, in this thread
94 or in other threads, is not executed.
95
96
97 .. function:: allocate_lock()
98
99 Return a new lock object. Methods of locks are described below. The lock is
100 initially unlocked.
101
102
103 .. function:: get_ident()
104
105 Return the 'thread identifier' of the current thread. This is a nonzero
106 integer. Its value has no direct meaning; it is intended as a magic cookie to
107 be used e.g. to index a dictionary of thread-specific data. Thread identifiers
108 may be recycled when a thread exits and another thread is created.
109
110
111 .. function:: get_native_id()
112
113 Return the native integral Thread ID of the current thread assigned by the kernel.
114 This is a non-negative integer.
115 Its value may be used to uniquely identify this particular thread system-wide
116 (until the thread terminates, after which the value may be recycled by the OS).
117
118 .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD.
119
120 .. versionadded:: 3.8
121
122 .. versionchanged:: 3.13
123 Added support for GNU/kFreeBSD.
124
125
126 .. function:: stack_size([size])
127
128 Return the thread stack size used when creating new threads. The optional
129 *size* argument specifies the stack size to be used for subsequently created
130 threads, and must be 0 (use platform or configured default) or a positive
131 integer value of at least 32,768 (32 KiB). If *size* is not specified,
132 0 is used. If changing the thread stack size is
133 unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is
134 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB
135 is currently the minimum supported stack size value to guarantee sufficient
136 stack space for the interpreter itself. Note that some platforms may have
137 particular restrictions on values for the stack size, such as requiring a
138 minimum stack size > 32 KiB or requiring allocation in multiples of the system
139 memory page size - platform documentation should be referred to for more
140 information (4 KiB pages are common; using multiples of 4096 for the stack size is
141 the suggested approach in the absence of more specific information).
142
143 .. availability:: Windows, pthreads.
144
145 Unix platforms with POSIX threads support.
146
147
148 .. data:: TIMEOUT_MAX
149
150 The maximum value allowed for the *timeout* parameter of
151 :meth:`Lock.acquire <threading.Lock.acquire>`. Specifying a timeout greater
152 than this value will raise an :exc:`OverflowError`.
153
154 .. versionadded:: 3.2
155
156
157 .. raw:: html
158
159 <!-- Keep the old URL fragments working (see gh-89554) -->
160 <span id='thread.lock.acquire'></span>
161 <span id='thread.lock.release'></span>
162 <span id='thread.lock.locked'></span>
163
164 .. class:: LockType
165
166 This is the type of lock objects.
167
168 Lock objects have the following methods:
169
170 .. method:: acquire(blocking=True, timeout=-1)
171
172 Without any optional argument, this method acquires the lock unconditionally, if
173 necessary waiting until it is released by another thread (only one thread at a
174 time can acquire a lock --- that's their reason for existence).
175
176 If the *blocking* argument is present, the action depends on its
177 value: if it is false, the lock is only acquired if it can be acquired
178 immediately without waiting, while if it is true, the lock is acquired
179 unconditionally as above.
180
181 If the floating-point *timeout* argument is present and positive, it
182 specifies the maximum wait time in seconds before returning. A negative
183 *timeout* argument specifies an unbounded wait. You cannot specify
184 a *timeout* if *blocking* is false.
185
186 The return value is ``True`` if the lock is acquired successfully,
187 ``False`` if not.
188
189 .. versionchanged:: 3.2
190 The *timeout* parameter is new.
191
192 .. versionchanged:: 3.2
193 Lock acquires can now be interrupted by signals on POSIX.
194
195 .. versionchanged:: 3.14
196 Lock acquires can now be interrupted by signals on Windows.
197
198 .. method:: release()
199
200 Releases the lock. The lock must have been acquired earlier, but not
201 necessarily by the same thread.
202
203 .. method:: locked()
204
205 Return the status of the lock: ``True`` if it has been acquired by some thread,
206 ``False`` if not.
207
208 In addition to these methods, lock objects can also be used via the
209 :keyword:`with` statement, e.g.::
210
211 import _thread
212
213 a_lock = _thread.allocate_lock()
214
215 with a_lock:
216 print("a_lock is locked while this executes")
217
218 **Caveats:**
219
220 .. index:: pair: module; signal
221
222 * Interrupts always go to the main thread (the :exc:`KeyboardInterrupt`
223 exception will be received by that thread.)
224
225 * Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
226 equivalent to calling :func:`_thread.exit`.
227
228 * When the main thread exits, it is system defined whether the other threads
229 survive. On most systems, they are killed without executing
230 :keyword:`try` ... :keyword:`finally` clauses or executing object
231 destructors.
232