blob: a6ce945c72057cd8da30011354d8b8362a8485b5 [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
46 Start a new thread and return its identifier. The thread executes the function
47 *function* with the argument list *args* (which must be a tuple). The optional
48 *kwargs* argument specifies a dictionary of keyword arguments. When the function
49 returns, the thread silently exits. When the function terminates with an
50 unhandled exception, a stack trace is printed and then the thread exits (but
51 other threads continue to run).
52
53
54.. function:: interrupt_main()
55
Matěj Cepl608876b2019-05-23 22:30:00 +020056 Simulate the effect of a :data:`signal.SIGINT` signal arriving in the main
57 thread. A thread can use this function to interrupt the main thread.
58
59 If :data:`signal.SIGINT` isn't handled by Python (it was set to
60 :data:`signal.SIG_DFL` or :data:`signal.SIG_IGN`), this function does
61 nothing.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl116aa622007-08-15 14:28:22 +000063
64.. function:: exit()
65
66 Raise the :exc:`SystemExit` exception. When not caught, this will cause the
67 thread to exit silently.
68
Christian Heimes5b5e81c2007-12-31 16:14:33 +000069..
70 function:: exit_prog(status)
71
72 Exit all threads and report the value of the integer argument
73 *status* as the exit status of the entire program.
74 **Caveat:** code in pending :keyword:`finally` clauses, in this thread
75 or in other threads, is not executed.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77
78.. function:: allocate_lock()
79
80 Return a new lock object. Methods of locks are described below. The lock is
81 initially unlocked.
82
83
84.. function:: get_ident()
85
86 Return the 'thread identifier' of the current thread. This is a nonzero
87 integer. Its value has no direct meaning; it is intended as a magic cookie to
88 be used e.g. to index a dictionary of thread-specific data. Thread identifiers
89 may be recycled when a thread exits and another thread is created.
90
91
Jake Teslerb121f632019-05-22 08:43:17 -070092.. function:: get_native_id()
93
94 Return the native integral Thread ID of the current thread assigned by the kernel.
95 This is a non-negative integer.
96 Its value may be used to uniquely identify this particular thread system-wide
97 (until the thread terminates, after which the value may be recycled by the OS).
98
99 .. availability:: Windows, FreeBSD, Linux, macOS.
100
101 .. versionadded:: 3.8
102
103
Georg Brandl116aa622007-08-15 14:28:22 +0000104.. function:: stack_size([size])
105
106 Return the thread stack size used when creating new threads. The optional
107 *size* argument specifies the stack size to be used for subsequently created
108 threads, and must be 0 (use platform or configured default) or a positive
Martin Panter31e7f502015-08-31 03:15:52 +0000109 integer value of at least 32,768 (32 KiB). If *size* is not specified,
110 0 is used. If changing the thread stack size is
Georg Brandl9a13b432012-04-05 09:53:04 +0200111 unsupported, a :exc:`RuntimeError` is raised. If the specified stack size is
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200112 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32 KiB
Georg Brandl116aa622007-08-15 14:28:22 +0000113 is currently the minimum supported stack size value to guarantee sufficient
114 stack space for the interpreter itself. Note that some platforms may have
115 particular restrictions on values for the stack size, such as requiring a
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200116 minimum stack size > 32 KiB or requiring allocation in multiples of the system
Georg Brandl116aa622007-08-15 14:28:22 +0000117 memory page size - platform documentation should be referred to for more
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200118 information (4 KiB pages are common; using multiples of 4096 for the stack size is
Georg Brandl116aa622007-08-15 14:28:22 +0000119 the suggested approach in the absence of more specific information).
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400120
121 .. availability:: Windows, systems with POSIX threads.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000124.. data:: TIMEOUT_MAX
125
126 The maximum value allowed for the *timeout* parameter of
Georg Brandl6faee4e2010-09-21 14:48:28 +0000127 :meth:`Lock.acquire`. Specifying a timeout greater than this value will
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000128 raise an :exc:`OverflowError`.
129
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000130 .. versionadded:: 3.2
131
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000132
Georg Brandl116aa622007-08-15 14:28:22 +0000133Lock objects have the following methods:
134
135
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000136.. method:: lock.acquire(waitflag=1, timeout=-1)
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000138 Without any optional argument, this method acquires the lock unconditionally, if
Georg Brandl116aa622007-08-15 14:28:22 +0000139 necessary waiting until it is released by another thread (only one thread at a
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000140 time can acquire a lock --- that's their reason for existence).
Georg Brandl116aa622007-08-15 14:28:22 +0000141
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000142 If the integer *waitflag* argument is present, the action depends on its
143 value: if it is zero, the lock is only acquired if it can be acquired
144 immediately without waiting, while if it is nonzero, the lock is acquired
145 unconditionally as above.
146
147 If the floating-point *timeout* argument is present and positive, it
148 specifies the maximum wait time in seconds before returning. A negative
149 *timeout* argument specifies an unbounded wait. You cannot specify
150 a *timeout* if *waitflag* is zero.
151
152 The return value is ``True`` if the lock is acquired successfully,
153 ``False`` if not.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Antoine Pitrouadbc0092010-04-19 14:05:51 +0000155 .. versionchanged:: 3.2
156 The *timeout* parameter is new.
157
Antoine Pitrou810023d2010-12-15 22:59:16 +0000158 .. versionchanged:: 3.2
159 Lock acquires can now be interrupted by signals on POSIX.
160
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162.. method:: lock.release()
163
164 Releases the lock. The lock must have been acquired earlier, but not
165 necessarily by the same thread.
166
167
168.. method:: lock.locked()
169
170 Return the status of the lock: ``True`` if it has been acquired by some thread,
171 ``False`` if not.
172
173In addition to these methods, lock objects can also be used via the
174:keyword:`with` statement, e.g.::
175
Georg Brandl2067bfd2008-05-25 13:05:15 +0000176 import _thread
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Georg Brandl2067bfd2008-05-25 13:05:15 +0000178 a_lock = _thread.allocate_lock()
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 with a_lock:
Collin Winterc79461b2007-09-01 23:34:30 +0000181 print("a_lock is locked while this executes")
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183**Caveats:**
184
185 .. index:: module: signal
186
187* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
188 exception will be received by an arbitrary thread. (When the :mod:`signal`
189 module is available, interrupts always go to the main thread.)
190
191* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
Georg Brandla6053b42009-09-01 08:11:14 +0000192 equivalent to calling :func:`_thread.exit`.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Georg Brandl116aa622007-08-15 14:28:22 +0000194* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
195 :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197* When the main thread exits, it is system defined whether the other threads
Antoine Pitroue4754bd2010-04-19 14:09:57 +0000198 survive. On most systems, they are killed without executing
199 :keyword:`try` ... :keyword:`finally` clauses or executing object
200 destructors.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202* When the main thread exits, it does not do any of its usual cleanup (except
203 that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
204 standard I/O files are not flushed.
Christian Heimes836baa52008-02-26 08:18:30 +0000205