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