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
15This module provides low-level primitives for working with multiple threads
16(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
17control sharing their global data space.  For synchronization, simple locks
18(also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided.
19The :mod:`threading` module provides an easier to use and higher-level
20threading 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
29This 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.. data:: LockType
40
41   This is the type of lock objects.
42
43
44.. function:: start_new_thread(function, args[, kwargs])
45
46   Start a new thread and return its identifier.  The thread executes the
47   function *function* with the argument list *args* (which must be a tuple).
48   The optional *kwargs* argument specifies a dictionary of keyword arguments.
49
50   When the function returns, the thread silently exits.
51
52   When the function terminates with an unhandled exception,
53   :func:`sys.unraisablehook` is called to handle the exception. The *object*
54   attribute of the hook argument is *function*. By default, a stack trace is
55   printed and then the thread exits (but other threads continue to run).
56
57   When the function raises a :exc:`SystemExit` exception, it is silently
58   ignored.
59
60   .. versionchanged:: 3.8
61      :func:`sys.unraisablehook` is now used to handle unhandled exceptions.
62
63
64.. function:: interrupt_main(signum=signal.SIGINT, /)
65
66   Simulate the effect of a signal arriving in the main thread.
67   A thread can use this function to interrupt the main thread, though
68   there is no guarantee that the interruption will happen immediately.
69
70   If given, *signum* is the number of the signal to simulate.
71   If *signum* is not given, :data:`signal.SIGINT` is simulated.
72
73   If the given signal isn't handled by Python (it was set to
74   :data:`signal.SIG_DFL` or :data:`signal.SIG_IGN`), this function does
75   nothing.
76
77   .. versionchanged:: 3.10
78      The *signum* argument is added to customize the signal number.
79
80   .. note::
81      This does not emit the corresponding signal but schedules a call to
82      the associated handler (if it exists).
83      If you want to truly emit the signal, use :func:`signal.raise_signal`.
84
85
86.. function:: exit()
87
88   Raise the :exc:`SystemExit` exception.  When not caught, this will cause the
89   thread to exit silently.
90
91..
92   function:: exit_prog(status)
93
94      Exit all threads and report the value of the integer argument
95      *status* as the exit status of the entire program.
96      **Caveat:** code in pending :keyword:`finally` clauses, in this thread
97      or in other threads, is not executed.
98
99
100.. function:: allocate_lock()
101
102   Return a new lock object.  Methods of locks are described below.  The lock is
103   initially unlocked.
104
105
106.. function:: get_ident()
107
108   Return the 'thread identifier' of the current thread.  This is a nonzero
109   integer.  Its value has no direct meaning; it is intended as a magic cookie to
110   be used e.g. to index a dictionary of thread-specific data.  Thread identifiers
111   may be recycled when a thread exits and another thread is created.
112
113
114.. function:: get_native_id()
115
116   Return the native integral Thread ID of the current thread assigned by the kernel.
117   This is a non-negative integer.
118   Its value may be used to uniquely identify this particular thread system-wide
119   (until the thread terminates, after which the value may be recycled by the OS).
120
121   .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
122
123   .. versionadded:: 3.8
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`. Specifying a timeout greater than this value will
152   raise an :exc:`OverflowError`.
153
154   .. versionadded:: 3.2
155
156
157Lock objects have the following methods:
158
159
160.. method:: lock.acquire(blocking=True, timeout=-1)
161
162   Without any optional argument, this method acquires the lock unconditionally, if
163   necessary waiting until it is released by another thread (only one thread at a
164   time can acquire a lock --- that's their reason for existence).
165
166   If the *blocking* argument is present, the action depends on its
167   value: if it is False, the lock is only acquired if it can be acquired
168   immediately without waiting, while if it is True, the lock is acquired
169   unconditionally as above.
170
171   If the floating-point *timeout* argument is present and positive, it
172   specifies the maximum wait time in seconds before returning.  A negative
173   *timeout* argument specifies an unbounded wait.  You cannot specify
174   a *timeout* if *blocking* is False.
175
176   The return value is ``True`` if the lock is acquired successfully,
177   ``False`` if not.
178
179   .. versionchanged:: 3.2
180      The *timeout* parameter is new.
181
182   .. versionchanged:: 3.2
183      Lock acquires can now be interrupted by signals on POSIX.
184
185
186.. method:: lock.release()
187
188   Releases the lock.  The lock must have been acquired earlier, but not
189   necessarily by the same thread.
190
191
192.. method:: lock.locked()
193
194   Return the status of the lock: ``True`` if it has been acquired by some thread,
195   ``False`` if not.
196
197In addition to these methods, lock objects can also be used via the
198:keyword:`with` statement, e.g.::
199
200   import _thread
201
202   a_lock = _thread.allocate_lock()
203
204   with a_lock:
205       print("a_lock is locked while this executes")
206
207**Caveats:**
208
209  .. index:: pair: module; signal
210
211* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
212  exception will be received by an arbitrary thread.  (When the :mod:`signal`
213  module is available, interrupts always go to the main thread.)
214
215* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
216  equivalent to calling :func:`_thread.exit`.
217
218* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
219  :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
220
221* When the main thread exits, it is system defined whether the other threads
222  survive.  On most systems, they are killed without executing
223  :keyword:`try` ... :keyword:`finally` clauses or executing object
224  destructors.
225
226* When the main thread exits, it does not do any of its usual cleanup (except
227  that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
228  standard I/O files are not flushed.
229
230