blob: 1e6452b7b826fdf33bd558ca6d6d54995bfab337 [file] [log] [blame]
Georg Brandl2067bfd2008-05-25 13:05:15 +00001:mod:`_thread` --- Low-level threading API
2==========================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl2067bfd2008-05-25 13:05:15 +00004.. module:: _thread
5 :synopsis: Low-level threading API.
Georg Brandl116aa622007-08-15 14:28:22 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. index::
8 single: light-weight processes
9 single: processes, light-weight
10 single: binary semaphores
11 single: semaphores, binary
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013--------------
14
Georg Brandl116aa622007-08-15 14:28:22 +000015This module provides low-level primitives for working with multiple threads
Thomas Wouters89d996e2007-09-08 17:39:28 +000016(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
Georg Brandl116aa622007-08-15 14:28:22 +000017control sharing their global data space. For synchronization, simple locks
Thomas Wouters89d996e2007-09-08 17:39:28 +000018(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.
Georg Brandl116aa622007-08-15 14:28:22 +000021
22.. index::
23 single: pthreads
24 pair: threads; POSIX
25
Antoine Pitroub43c4ca2017-09-18 22:04:20 +020026.. versionchanged:: 3.7
27 This module used to be optional, it is now always available.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Antoine Pitroub43c4ca2017-09-18 22:04:20 +020029This module defines the following constants and functions:
Georg Brandl116aa622007-08-15 14:28:22 +000030
31.. exception:: error
32
33 Raised on thread-specific errors.
34
Antoine Pitroufcf81fd2011-02-28 22:03:34 +000035 .. versionchanged:: 3.3
36 This is now a synonym of the built-in :exc:`RuntimeError`.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
39.. data:: LockType
40
41 This is the type of lock objects.
42
43
44.. function:: start_new_thread(function, args[, kwargs])
45
Victor Stinner8b095002019-05-29 02:57:56 +020046 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.
Georg Brandl116aa622007-08-15 14:28:22 +000062
63
Antoine Pitrouba251c22021-03-11 23:35:45 +010064.. function:: interrupt_main(signum=signal.SIGINT, /)
Georg Brandl116aa622007-08-15 14:28:22 +000065
Antoine Pitrouba251c22021-03-11 23:35:45 +010066 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.
Matěj Cepl608876b2019-05-23 22:30:00 +020069
Antoine Pitrouba251c22021-03-11 23:35:45 +010070 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
Matěj Cepl608876b2019-05-23 22:30:00 +020074 :data:`signal.SIG_DFL` or :data:`signal.SIG_IGN`), this function does
75 nothing.
Georg Brandl116aa622007-08-15 14:28:22 +000076
Antoine Pitrouba251c22021-03-11 23:35:45 +010077 .. 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
Georg Brandl116aa622007-08-15 14:28:22 +000085
86.. function:: exit()
87
88 Raise the :exc:`SystemExit` exception. When not caught, this will cause the
89 thread to exit silently.
90
Christian Heimes5b5e81c2007-12-31 16:14:33 +000091..
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.
Georg Brandl116aa622007-08-15 14:28:22 +000098
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
Jake Teslerb121f632019-05-22 08:43:17 -0700114.. 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
Michael Feltd0eeb932019-06-14 00:34:46 +0200121 .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
Jake Teslerb121f632019-05-22 08:43:17 -0700122
123 .. versionadded:: 3.8
124
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126.. 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
Martin Panter31e7f502015-08-31 03:15:52 +0000131 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
Georg Brandl9a13b432012-04-05 09:53:04 +0200133 unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200134 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB
Georg Brandl116aa622007-08-15 14:28:22 +0000135 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
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200138 minimum stack size > 32 KiB or requiring allocation in multiples of the system
Georg Brandl116aa622007-08-15 14:28:22 +0000139 memory page size - platform documentation should be referred to for more
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200140 information (4 KiB pages are common; using multiples of 4096 for the stack size is
Georg Brandl116aa622007-08-15 14:28:22 +0000141 the suggested approach in the absence of more specific information).
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400142
143 .. availability:: Windows, systems with POSIX threads.
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000146.. data:: TIMEOUT_MAX
147
148 The maximum value allowed for the *timeout* parameter of
Georg Brandl6faee4e2010-09-21 14:48:28 +0000149 :meth:`Lock.acquire`. Specifying a timeout greater than this value will
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000150 raise an :exc:`OverflowError`.
151
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000152 .. versionadded:: 3.2
153
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000154
Georg Brandl116aa622007-08-15 14:28:22 +0000155Lock objects have the following methods:
156
157
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000158.. method:: lock.acquire(waitflag=1, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000160 Without any optional argument, this method acquires the lock unconditionally, if
Georg Brandl116aa622007-08-15 14:28:22 +0000161 necessary waiting until it is released by another thread (only one thread at a
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000162 time can acquire a lock --- that's their reason for existence).
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000164 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000177 .. versionchanged:: 3.2
178 The *timeout* parameter is new.
179
Antoine Pitrou810023d2010-12-15 22:59:16 +0000180 .. versionchanged:: 3.2
181 Lock acquires can now be interrupted by signals on POSIX.
182
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184.. 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
Georg Brandl2067bfd2008-05-25 13:05:15 +0000198 import _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000199
Georg Brandl2067bfd2008-05-25 13:05:15 +0000200 a_lock = _thread.allocate_lock()
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202 with a_lock:
Collin Winterc79461b2007-09-01 23:34:30 +0000203 print("a_lock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000204
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
Georg Brandla6053b42009-09-01 08:11:14 +0000214 equivalent to calling :func:`_thread.exit`.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Georg Brandl116aa622007-08-15 14:28:22 +0000216* 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
Georg Brandl116aa622007-08-15 14:28:22 +0000219* When the main thread exits, it is system defined whether the other threads
Antoine Pitroue4754bd2010-04-19 14:09:57 +0000220 survive. On most systems, they are killed without executing
221 :keyword:`try` ... :keyword:`finally` clauses or executing object
222 destructors.
Georg Brandl116aa622007-08-15 14:28:22 +0000223
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.
Christian Heimes836baa52008-02-26 08:18:30 +0000227