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, systems with POSIX threads.
144
145
146.. data:: TIMEOUT_MAX
147
148   The maximum value allowed for the *timeout* parameter of
149   :meth:`Lock.acquire`. Specifying a timeout greater than this value will
150   raise an :exc:`OverflowError`.
151
152   .. versionadded:: 3.2
153
154
155Lock objects have the following methods:
156
157
158.. method:: lock.acquire(waitflag=1, timeout=-1)
159
160   Without any optional argument, this method acquires the lock unconditionally, if
161   necessary waiting until it is released by another thread (only one thread at a
162   time can acquire a lock --- that's their reason for existence).
163
164   If the integer *waitflag* argument is present, the action depends on its
165   value: if it is zero, the lock is only acquired if it can be acquired
166   immediately without waiting, while if it is nonzero, the lock is acquired
167   unconditionally as above.
168
169   If the floating-point *timeout* argument is present and positive, it
170   specifies the maximum wait time in seconds before returning.  A negative
171   *timeout* argument specifies an unbounded wait.  You cannot specify
172   a *timeout* if *waitflag* is zero.
173
174   The return value is ``True`` if the lock is acquired successfully,
175   ``False`` if not.
176
177   .. versionchanged:: 3.2
178      The *timeout* parameter is new.
179
180   .. versionchanged:: 3.2
181      Lock acquires can now be interrupted by signals on POSIX.
182
183
184.. method:: lock.release()
185
186   Releases the lock.  The lock must have been acquired earlier, but not
187   necessarily by the same thread.
188
189
190.. method:: lock.locked()
191
192   Return the status of the lock: ``True`` if it has been acquired by some thread,
193   ``False`` if not.
194
195In addition to these methods, lock objects can also be used via the
196:keyword:`with` statement, e.g.::
197
198   import _thread
199
200   a_lock = _thread.allocate_lock()
201
202   with a_lock:
203       print("a_lock is locked while this executes")
204
205**Caveats:**
206
207  .. index:: module: signal
208
209* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
210  exception will be received by an arbitrary thread.  (When the :mod:`signal`
211  module is available, interrupts always go to the main thread.)
212
213* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
214  equivalent to calling :func:`_thread.exit`.
215
216* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
217  :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
218
219* When the main thread exits, it is system defined whether the other threads
220  survive.  On most systems, they are killed without executing
221  :keyword:`try` ... :keyword:`finally` clauses or executing object
222  destructors.
223
224* When the main thread exits, it does not do any of its usual cleanup (except
225  that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
226  standard I/O files are not flushed.
227
228