blob: afe8cbeffbc1044052498412d790154220f203eb [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`thread` --- Multiple threads of control
3=============================================
4
5.. module:: thread
6 :synopsis: Create multiple threads of control within one interpreter.
7
8
9.. index::
10 single: light-weight processes
11 single: processes, light-weight
12 single: binary semaphores
13 single: semaphores, binary
14
15This module provides low-level primitives for working with multiple threads
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000016(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
Georg Brandl8ec7f652007-08-15 14:28:01 +000017control sharing their global data space. For synchronization, simple locks
Mark Summerfieldfcb444a2007-09-04 08:16:15 +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 Brandl8ec7f652007-08-15 14:28:01 +000021
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 constant and functions:
33
34
35.. exception:: error
36
37 Raised on thread-specific errors.
38
39
40.. data:: LockType
41
42 This is the type of lock objects.
43
44
45.. function:: start_new_thread(function, args[, kwargs])
46
47 Start a new thread and return its identifier. The thread executes the function
48 *function* with the argument list *args* (which must be a tuple). The optional
49 *kwargs* argument specifies a dictionary of keyword arguments. When the function
50 returns, the thread silently exits. When the function terminates with an
51 unhandled exception, a stack trace is printed and then the thread exits (but
52 other threads continue to run).
53
54
55.. function:: interrupt_main()
56
57 Raise a :exc:`KeyboardInterrupt` exception in the main thread. A subthread can
58 use this function to interrupt the main thread.
59
60 .. versionadded:: 2.3
61
62
63.. function:: exit()
64
65 Raise the :exc:`SystemExit` exception. When not caught, this will cause the
66 thread to exit silently.
67
Georg Brandlb19be572007-12-29 10:57:00 +000068..
69 function:: exit_prog(status)
70
71 Exit all threads and report the value of the integer argument
72 *status* as the exit status of the entire program.
73 **Caveat:** code in pending :keyword:`finally` clauses, in this thread
74 or in other threads, is not executed.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76
77.. function:: allocate_lock()
78
79 Return a new lock object. Methods of locks are described below. The lock is
80 initially unlocked.
81
82
83.. function:: get_ident()
84
85 Return the 'thread identifier' of the current thread. This is a nonzero
86 integer. Its value has no direct meaning; it is intended as a magic cookie to
87 be used e.g. to index a dictionary of thread-specific data. Thread identifiers
88 may be recycled when a thread exits and another thread is created.
89
90
91.. function:: stack_size([size])
92
93 Return the thread stack size used when creating new threads. The optional
94 *size* argument specifies the stack size to be used for subsequently created
95 threads, and must be 0 (use platform or configured default) or a positive
96 integer value of at least 32,768 (32kB). If changing the thread stack size is
97 unsupported, a :exc:`ThreadError` is raised. If the specified stack size is
98 invalid, a :exc:`ValueError` is raised and the stack size is unmodified. 32kB
99 is currently the minimum supported stack size value to guarantee sufficient
100 stack space for the interpreter itself. Note that some platforms may have
101 particular restrictions on values for the stack size, such as requiring a
102 minimum stack size > 32kB or requiring allocation in multiples of the system
103 memory page size - platform documentation should be referred to for more
104 information (4kB pages are common; using multiples of 4096 for the stack size is
105 the suggested approach in the absence of more specific information).
106 Availability: Windows, systems with POSIX threads.
107
108 .. versionadded:: 2.5
109
110Lock objects have the following methods:
111
112
113.. method:: lock.acquire([waitflag])
114
115 Without the optional argument, this method acquires the lock unconditionally, if
116 necessary waiting until it is released by another thread (only one thread at a
117 time can acquire a lock --- that's their reason for existence). If the integer
118 *waitflag* argument is present, the action depends on its value: if it is zero,
119 the lock is only acquired if it can be acquired immediately without waiting,
120 while if it is nonzero, the lock is acquired unconditionally as before. The
121 return value is ``True`` if the lock is acquired successfully, ``False`` if not.
122
123
124.. method:: lock.release()
125
126 Releases the lock. The lock must have been acquired earlier, but not
127 necessarily by the same thread.
128
129
130.. method:: lock.locked()
131
132 Return the status of the lock: ``True`` if it has been acquired by some thread,
133 ``False`` if not.
134
135In addition to these methods, lock objects can also be used via the
136:keyword:`with` statement, e.g.::
137
138 from __future__ import with_statement
139 import thread
140
141 a_lock = thread.allocate_lock()
142
143 with a_lock:
144 print "a_lock is locked while this executes"
145
146**Caveats:**
147
148 .. index:: module: signal
149
150* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
151 exception will be received by an arbitrary thread. (When the :mod:`signal`
152 module is available, interrupts always go to the main thread.)
153
154* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
155 equivalent to calling :func:`exit`.
156
157* Not all built-in functions that may block waiting for I/O allow other threads
158 to run. (The most popular ones (:func:`time.sleep`, :meth:`file.read`,
159 :func:`select.select`) work as expected.)
160
161* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
162 :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.
163
164 .. index:: pair: threads; IRIX
165
166* When the main thread exits, it is system defined whether the other threads
167 survive. On SGI IRIX using the native thread implementation, they survive. On
168 most other systems, they are killed without executing :keyword:`try` ...
169 :keyword:`finally` clauses or executing object destructors.
170
171* When the main thread exits, it does not do any of its usual cleanup (except
172 that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
173 standard I/O files are not flushed.
174