• 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
26The module is optional.  It is supported on Windows, Linux, SGI IRIX, Solaris
272.x, as well as on systems that have a POSIX thread (a.k.a. "pthread")
28implementation.  For systems lacking the :mod:`_thread` module, the
29:mod:`_dummy_thread` module is available. It duplicates this module's interface
30and can be used as a drop-in replacement.
31
32It defines the following constants and functions:
33
34
35.. exception:: error
36
37   Raised on thread-specific errors.
38
39   .. versionchanged:: 3.3
40      This is now a synonym of the built-in :exc:`RuntimeError`.
41
42
43.. data:: LockType
44
45   This is the type of lock objects.
46
47
48.. function:: start_new_thread(function, args[, kwargs])
49
50   Start a new thread and return its identifier.  The thread executes the function
51   *function* with the argument list *args* (which must be a tuple).  The optional
52   *kwargs* argument specifies a dictionary of keyword arguments. When the function
53   returns, the thread silently exits.  When the function terminates with an
54   unhandled exception, a stack trace is printed and then the thread exits (but
55   other threads continue to run).
56
57
58.. function:: interrupt_main()
59
60   Raise a :exc:`KeyboardInterrupt` exception in the main thread.  A subthread can
61   use this function to interrupt the main thread.
62
63
64.. function:: exit()
65
66   Raise the :exc:`SystemExit` exception.  When not caught, this will cause the
67   thread to exit silently.
68
69..
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.
76
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
92.. function:: stack_size([size])
93
94   Return the thread stack size used when creating new threads.  The optional
95   *size* argument specifies the stack size to be used for subsequently created
96   threads, and must be 0 (use platform or configured default) or a positive
97   integer value of at least 32,768 (32 KiB). If *size* is not specified,
98   0 is used.  If changing the thread stack size is
99   unsupported, a :exc:`RuntimeError` is raised.  If the specified stack size is
100   invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32 KiB
101   is currently the minimum supported stack size value to guarantee sufficient
102   stack space for the interpreter itself.  Note that some platforms may have
103   particular restrictions on values for the stack size, such as requiring a
104   minimum stack size > 32 KiB or requiring allocation in multiples of the system
105   memory page size - platform documentation should be referred to for more
106   information (4 KiB pages are common; using multiples of 4096 for the stack size is
107   the suggested approach in the absence of more specific information).
108   Availability: Windows, systems with POSIX threads.
109
110
111.. data:: TIMEOUT_MAX
112
113   The maximum value allowed for the *timeout* parameter of
114   :meth:`Lock.acquire`. Specifying a timeout greater than this value will
115   raise an :exc:`OverflowError`.
116
117   .. versionadded:: 3.2
118
119
120Lock objects have the following methods:
121
122
123.. method:: lock.acquire(waitflag=1, timeout=-1)
124
125   Without any optional argument, this method acquires the lock unconditionally, if
126   necessary waiting until it is released by another thread (only one thread at a
127   time can acquire a lock --- that's their reason for existence).
128
129   If the integer *waitflag* argument is present, the action depends on its
130   value: if it is zero, the lock is only acquired if it can be acquired
131   immediately without waiting, while if it is nonzero, the lock is acquired
132   unconditionally as above.
133
134   If the floating-point *timeout* argument is present and positive, it
135   specifies the maximum wait time in seconds before returning.  A negative
136   *timeout* argument specifies an unbounded wait.  You cannot specify
137   a *timeout* if *waitflag* is zero.
138
139   The return value is ``True`` if the lock is acquired successfully,
140   ``False`` if not.
141
142   .. versionchanged:: 3.2
143      The *timeout* parameter is new.
144
145   .. versionchanged:: 3.2
146      Lock acquires can now be interrupted by signals on POSIX.
147
148
149.. method:: lock.release()
150
151   Releases the lock.  The lock must have been acquired earlier, but not
152   necessarily by the same thread.
153
154
155.. method:: lock.locked()
156
157   Return the status of the lock: ``True`` if it has been acquired by some thread,
158   ``False`` if not.
159
160In addition to these methods, lock objects can also be used via the
161:keyword:`with` statement, e.g.::
162
163   import _thread
164
165   a_lock = _thread.allocate_lock()
166
167   with a_lock:
168       print("a_lock is locked while this executes")
169
170**Caveats:**
171
172  .. index:: module: signal
173
174* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
175  exception will be received by an arbitrary thread.  (When the :mod:`signal`
176  module is available, interrupts always go to the main thread.)
177
178* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
179  equivalent to calling :func:`_thread.exit`.
180
181* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
182  :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
183
184* When the main thread exits, it is system defined whether the other threads
185  survive.  On most systems, they are killed without executing
186  :keyword:`try` ... :keyword:`finally` clauses or executing object
187  destructors.
188
189* When the main thread exits, it does not do any of its usual cleanup (except
190  that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
191  standard I/O files are not flushed.
192
193