17.1. threading — Thread-based parallelism¶
Source code: Lib/threading.py
This module constructs higher-level threading interfaces on top of the lower
level _thread module. See also the queue module.
3.7 版更變: This module used to be optional, it is now always available.
備註
While they are not listed below, the camelCase names used for some
methods and functions in this module in the Python 2.x series are still
supported by this module.
This module defines the following functions:
-
threading.active_count()¶ Return the number of
Threadobjects currently alive. The returned count is equal to the length of the list returned byenumerate().
-
threading.current_thread()¶ Return the current
Threadobject, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through thethreadingmodule, a dummy thread object with limited functionality is returned.
-
threading.get_ident()¶ Return the 『thread identifier』 of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.
3.3 版新加入.
-
threading.enumerate()¶ Return a list of all
Threadobjects currently alive. The list includes daemonic threads, dummy thread objects created bycurrent_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.
-
threading.main_thread()¶ Return the main
Threadobject. In normal conditions, the main thread is the thread from which the Python interpreter was started.3.4 版新加入.
-
threading.settrace(func)¶ Set a trace function for all threads started from the
threadingmodule. The func will be passed tosys.settrace()for each thread, before itsrun()method is called.
-
threading.setprofile(func)¶ Set a profile function for all threads started from the
threadingmodule. The func will be passed tosys.setprofile()for each thread, before itsrun()method is called.
-
threading.stack_size([size])¶ Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a
RuntimeErroris raised. If the specified stack size is invalid, aValueErroris raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads.
This module also defines the following constant:
-
threading.TIMEOUT_MAX¶ The maximum value allowed for the timeout parameter of blocking functions (
Lock.acquire(),RLock.acquire(),Condition.wait(), etc.). Specifying a timeout greater than this value will raise anOverflowError.3.2 版新加入.
This module defines a number of classes, which are detailed in the sections below.
The design of this module is loosely based on Java’s threading model. However,
where Java makes locks and condition variables basic behavior of every object,
they are separate objects in Python. Python’s Thread class supports a
subset of the behavior of Java’s Thread class; currently, there are no
priorities, no thread groups, and threads cannot be destroyed, stopped,
suspended, resumed, or interrupted. The static methods of Java’s Thread class,
when implemented, are mapped to module-level functions.
All of the methods described below are executed atomically.
17.1.1. Thread-Local Data¶
Thread-local data is data whose values are thread specific. To manage
thread-local data, just create an instance of local (or a
subclass) and store attributes on it:
mydata = threading.local()
mydata.x = 1
The instance’s values will be different for separate threads.
-
class
threading.local¶ A class that represents thread-local data.
For more details and extensive examples, see the documentation string of the
_threading_localmodule.
17.1.2. Thread Objects¶
The Thread class represents an activity that is run in a separate
thread of control. There are two ways to specify the activity: by passing a
callable object to the constructor, or by overriding the run()
method in a subclass. No other methods (except for the constructor) should be
overridden in a subclass. In other words, only override the
__init__() and run() methods of this class.
Once a thread object is created, its activity must be started by calling the
thread’s start() method. This invokes the run()
method in a separate thread of control.
Once the thread’s activity is started, the thread is considered 『alive』. It
stops being alive when its run() method terminates – either
normally, or by raising an unhandled exception. The is_alive()
method tests whether the thread is alive.
Other threads can call a thread’s join() method. This blocks
the calling thread until the thread whose join() method is
called is terminated.
A thread has a name. The name can be passed to the constructor, and read or
changed through the name attribute.
A thread can be flagged as a 「daemon thread」. The significance of this flag is
that the entire Python program exits when only daemon threads are left. The
initial value is inherited from the creating thread. The flag can be set
through the daemon property or the daemon constructor
argument.
備註
Daemon threads are abruptly stopped at shutdown. Their resources (such
as open files, database transactions, etc.) may not be released properly.
If you want your threads to stop gracefully, make them non-daemonic and
use a suitable signalling mechanism such as an Event.
There is a 「main thread」 object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.
There is the possibility that 「dummy thread objects」 are created. These are
thread objects corresponding to 「alien threads」, which are threads of control
started outside the threading module, such as directly from C code. Dummy
thread objects have limited functionality; they are always considered alive and
daemonic, and cannot be join()ed. They are never deleted,
since it is impossible to detect the termination of alien threads.
-
class
threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)¶ This constructor should always be called with keyword arguments. Arguments are:
group should be
None; reserved for future extension when aThreadGroupclass is implemented.target is the callable object to be invoked by the
run()method. Defaults toNone, meaning nothing is called.name is the thread name. By default, a unique name is constructed of the form 「Thread-N」 where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to
().kwargs is a dictionary of keyword arguments for the target invocation. Defaults to
{}.If not
None, daemon explicitly sets whether the thread is daemonic. IfNone(the default), the daemonic property is inherited from the current thread.If the subclass overrides the constructor, it must make sure to invoke the base class constructor (
Thread.__init__()) before doing anything else to the thread.3.3 版更變: Added the daemon argument.
-
start()¶ Start the thread’s activity.
It must be called at most once per thread object. It arranges for the object’s
run()method to be invoked in a separate thread of control.This method will raise a
RuntimeErrorif called more than once on the same thread object.
-
run()¶ Method representing the thread’s activity.
You may override this method in a subclass. The standard
run()method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
-
join(timeout=None)¶ Wait until the thread terminates. This blocks the calling thread until the thread whose
join()method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.When the timeout argument is present and not
None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). Asjoin()always returnsNone, you must callis_alive()afterjoin()to decide whether a timeout happened – if the thread is still alive, thejoin()call timed out.When the timeout argument is not present or
None, the operation will block until the thread terminates.A thread can be
join()ed many times.join()raises aRuntimeErrorif an attempt is made to join the current thread as that would cause a deadlock. It is also an error tojoin()a thread before it has been started and attempts to do so raise the same exception.
-
name¶ A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
-
ident¶ The 『thread identifier』 of this thread or
Noneif the thread has not been started. This is a nonzero integer. See theget_ident()function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.
-
is_alive()¶ Return whether the thread is alive.
This method returns
Truejust before therun()method starts until just after therun()method terminates. The module functionenumerate()returns a list of all alive threads.
-
daemon¶ A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before
start()is called, otherwiseRuntimeErroris raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default todaemon=False.The entire Python program exits when no alive non-daemon threads are left.
-
CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread
can execute Python code at once (even though certain performance-oriented
libraries might overcome this limitation).
If you want your application to make better use of the computational
resources of multi-core machines, you are advised to use
multiprocessing or concurrent.futures.ProcessPoolExecutor.
However, threading is still an appropriate model if you want to run
multiple I/O-bound tasks simultaneously.
17.1.3. Lock Objects¶
A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked. In Python, it is currently the lowest level
synchronization primitive available, implemented directly by the _thread
extension module.
A primitive lock is in one of two states, 「locked」 or 「unlocked」. It is created
in the unlocked state. It has two basic methods, acquire() and
release(). When the state is unlocked, acquire()
changes the state to locked and returns immediately. When the state is locked,
acquire() blocks until a call to release() in another
thread changes it to unlocked, then the acquire() call resets it
to locked and returns. The release() method should only be
called in the locked state; it changes the state to unlocked and returns
immediately. If an attempt is made to release an unlocked lock, a
RuntimeError will be raised.
Locks also support the context management protocol.
When more than one thread is blocked in acquire() waiting for the
state to turn to unlocked, only one thread proceeds when a release()
call resets the state to unlocked; which one of the waiting threads proceeds
is not defined, and may vary across implementations.
All methods are executed atomically.
- class
