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