• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   .. audit-event:: _thread.start_new_thread function,args,kwargs start_new_thread
61
62   .. versionchanged:: 3.8
63      :func:`sys.unraisablehook` is now used to handle unhandled exceptions.
64
65
66.. function:: interrupt_main(signum=signal.SIGINT, /)
67
68   Simulate the effect of a signal arriving in the main thread.
69   A thread can use this function to interrupt the main thread, though
70   there is no guarantee that the interruption will happen immediately.
71
72   If given, *signum* is the number of the signal to simulate.
73   If *signum* is not given, :const:`signal.SIGINT` is simulated.
74
75   If the given signal isn't handled by Python (it was set to
76   :const:`signal.SIG_DFL` or :const:`signal.SIG_IGN`), this function does
77   nothing.
78
79   .. versionchanged:: 3.10
80      The *signum* argument is added to customize the signal number.
81
82   .. note::
83      This does not emit the corresponding signal but schedules a call to
84      the associated handler (if it exists).
85      If you want to truly emit the signal, use :func:`signal.raise_signal`.
86
87
88.. function:: exit()
89
90   Raise the :exc:`SystemExit` exception.  When not caught, this will cause the
91   thread to exit silently.
92
93..
94   function:: exit_prog(status)
95
96      Exit all threads and report the value of the integer argument
97      *status* as the exit status of the entire program.
98      **Caveat:** code in pending :keyword:`finally` clauses, in this thread
99      or in other threads, is not executed.
100
101
102.. function:: allocate_lock()
103
104   Return a new lock object.  Methods of locks are described below.  The lock is
105   initially unlocked.
106
107
108.. function:: get_ident()
109
110   Return the 'thread identifier' of the current thread.  This is a nonzero
111   integer.  Its value has no direct meaning; it is intended as a magic cookie to
112   be used e.g. to index a dictionary of thread-specific data.  Thread identifiers
113   may be recycled when a thread exits and another thread is created.
114
115
116.. function:: get_native_id()
117
118   Return the native integral Thread ID of the current thread assigned by the kernel.
119   This is a non-negative integer.
120   Its value may be used to uniquely identify this particular thread system-wide
121   (until the thread terminates, after which the value may be recycled by the OS).
122
123   .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD, GNU/kFreeBSD.
124
125   .. versionadded:: 3.8
126
127   .. versionchanged:: 3.13
128      Added support for GNU/kFreeBSD.
129
130
131.. function:: stack_size([size])
132
133   Return the thread stack size used when creating new threads.  The optional
134   *size* argument specifies the stack size to be used for subsequently created
135   threads, and must be 0 (use platform or configured default) or a positive
136   integer value of at least 32,768 (32 KiB). If *size* is not specified,
137   0 is used.  If changing the thread stack size is
138   unsupported, a :exc:`RuntimeError` is raised.  If the specified stack size is
139   invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32 KiB
140   is currently the minimum supported stack size value to guarantee sufficient
141   stack space for the interpreter itself.  Note that some platforms may have
142   particular restrictions on values for the stack size, such as requiring a
143   minimum stack size > 32 KiB or requiring allocation in multiples of the system
144   memory page size - platform documentation should be referred to for more
145   information (4 KiB pages are common; using multiples of 4096 for the stack size is
146   the suggested approach in the absence of more specific information).
147
148   .. availability:: Windows, pthreads.
149
150      Unix platforms with POSIX threads support.
151
152
153.. data:: TIMEOUT_MAX
154
155   The maximum value allowed for the *timeout* parameter of
156   :meth:`Lock.acquire <threading.Lock.acquire>`. Specifying a timeout greater
157   than this value will raise an :exc:`OverflowError`.
158
159   .. versionadded:: 3.2
160
161
162Lock objects have the following methods:
163
164
165.. method:: lock.acquire(blocking=True, timeout=-1)
166
167   Without any optional argument, this method acquires the lock unconditionally, if
168   necessary waiting until it is released by another thread (only one thread at a
169   time can acquire a lock --- that's their reason for existence).
170
171   If the *blocking* argument is present, the action depends on its
172   value: if it is false, the lock is only acquired if it can be acquired
173   immediately without waiting, while if it is true, the lock is acquired
174   unconditionally as above.
175
176   If the floating-point *timeout* argument is present and positive, it
177   specifies the maximum wait time in seconds before returning.  A negative
178   *timeout* argument specifies an unbounded wait.  You cannot specify
179   a *timeout* if *blocking* is false.
180
181   The return value is ``True`` if the lock is acquired successfully,
182   ``False`` if not.
183
184   .. versionchanged:: 3.2
185      The *timeout* parameter is new.
186
187   .. versionchanged:: 3.2
188      Lock acquires can now be interrupted by signals on POSIX.
189
190
191.. method:: lock.release()
192
193   Releases the lock.  The lock must have been acquired earlier, but not
194   necessarily by the same thread.
195
196
197.. method:: lock.locked()
198
199   Return the status of the lock: ``True`` if it has been acquired by some thread,
200   ``False`` if not.
201
202In addition to these methods, lock objects can also be used via the
203:keyword:`with` statement, e.g.::
204
205   import _thread
206
207   a_lock = _thread.allocate_lock()
208
209   with a_lock:
210       print("a_lock is locked while this executes")
211
212**Caveats:**
213
214.. index:: pair: module; signal
215
216* Interrupts always go to the main thread (the :exc:`KeyboardInterrupt`
217  exception will be received by that thread.)
218
219* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
220  equivalent to calling :func:`_thread.exit`.
221
222* It is platform-dependent whether the :meth:`~threading.Lock.acquire` method
223  on a lock can be interrupted (so that the :exc:`KeyboardInterrupt` exception
224  will happen immediately, rather than only after the lock has been acquired or
225  the operation has timed out). It can be interrupted on POSIX, but not on
226  Windows.
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
233