_thread
— Low-level threading API低级线程API¶
This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. 该模块提供了用于处理多个线程(也称为轻量级进程或任务)的低级原语——多个控制线程共享其全局数据空间。For synchronization, simple locks (also called mutexes or binary semaphores) are provided. 对于同步,提供了简单的锁(也称为互斥锁或二进制信号量)。The threading
module provides an easier to use and higher-level threading API built on top of this module.threading
模块提供了一个更易于使用和更高级别的线程API构建在此模块之上。
Changed in version 3.7:版本3.7中更改: This module used to be optional, it is now always available.这个模块过去是可选的,现在总是可用的。
This module defines the following constants and functions:此模块定义以下常量和函数:
-
exception
_thread.
error
¶ Raised on thread-specific errors.在线程特定错误时引发。Changed in version 3.3:版本3.3中更改:This is now a synonym of the built-in这现在是内置RuntimeError
.RuntimeError
的同义词。
-
_thread.
LockType
¶ This is the type of lock objects.这是锁定对象的类型。
-
_thread.
start_new_thread
(function, args[, kwargs])¶ Start a new thread and return its identifier.启动一个新线程并返回其标识符。The thread executes the function function with the argument list args (which must be a tuple).线程使用参数列表args(必须是元组)执行函数function。The optional kwargs argument specifies a dictionary of keyword arguments.When the function returns, the thread silently exits.当函数返回时,线程将静默退出。When the function terminates with an unhandled exception,当函数因未处理的异常而终止时,将调用sys.unraisablehook()
is called to handle the exception.sys.unraisablehook()
来处理该异常。The object attribute of the hook argument is function.hook参数的object属性是function。By default, a stack trace is printed and then the thread exits (but other threads continue to run).默认情况下,打印堆栈跟踪,然后线程退出(但其他线程继续运行)。When the function raises a当函数引发SystemExit
exception, it is silently ignored.SystemExit
异常时,它将被静默地忽略。Changed in version 3.8:版本3.8中更改:sys.unraisablehook()
is now used to handle unhandled exceptions.现在用于处理未处理的异常。
-
_thread.
interrupt_main
(signum=signal.SIGINT, /)¶ Simulate the effect of a signal arriving in the main thread.模拟信号到达主线程的效果。A thread can use this function to interrupt the main thread, though there is no guarantee that the interruption will happen immediately.线程可以使用此函数来中断主线程,尽管不能保证中断会立即发生。If given, signum is the number of the signal to simulate.如果给定,signum是要模拟的信号的数量。If signum is not given,如果没有给出signum,则模拟signal.SIGINT
is simulated.signal.SIGINT
。If the given signal isn’t handled by Python (it was set to如果给定的信号不是由Python处理的(它被设置为signal.SIG_DFL
orsignal.SIG_IGN
), this function does nothing.signal.SIG_DFL
或signal.SIG_IGN
),则此函数不执行任何操作。Changed in version 3.10:版本3.10中更改:The signum argument is added to customize the signal number.添加signum参数是为了自定义信号编号。Note
This does not emit the corresponding signal but schedules a call to the associated handler (if it exists).这不会发出相应的信号,而是调度对相关处理程序(如果存在)的调用。If you want to truly emit the signal, use如果您想真正发出信号,请使用signal.raise_signal()
.signal.raise_signal()
。
-
_thread.
exit
()¶ Raise the引发SystemExit
exception.SystemExit
异常。When not caught, this will cause the thread to exit silently.如果没有被捕获,这将导致线程静默退出。
-
_thread.
allocate_lock
()¶ Return a new lock object. Methods of locks are described below. The lock is initially unlocked.返回一个新的锁定对象。锁的方法如下所述。锁最初处于解锁状态。
-
_thread.
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.这是一个非零整数。它的价值没有直接意义;它旨在作为一个神奇的cookie来使用,例如为线程特定数据的字典编制索引。Thread identifiers may be recycled when a thread exits and another thread is created.当一个线程退出并创建另一个线程时,可以回收线程标识符。
-
_thread.
get_native_id
()¶ Return the native integral Thread ID of the current thread assigned by the kernel.返回内核分配的当前线程的本机积分线程ID。This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS).这是一个非负整数。它的值可以用于在系统范围内唯一标识该特定线程(直到线程终止,之后该值可以由OS回收)。Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
New in version 3.8.版本3.8中新增。
-
_thread.
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).可选的size参数指定要用于后续创建的线程的堆栈大小,并且必须为0(使用平台或配置的默认值)或至少为32768(32 KiB)的正整数值。If size is not specified, 0 is used.如果未指定大小,则使用0。If changing the thread stack size is unsupported, a如果不支持更改线程堆栈大小,则会引发RuntimeError
is raised.RuntimeError
。If the specified stack size is invalid, a如果指定的堆栈大小无效,则会引发ValueError
is 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.ValueError
,并且堆栈大小不会更改。32KiB是当前支持的最小堆栈大小值,以保证解释器本身有足够的堆栈空间。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).注意,一些平台可能对堆栈大小的值具有特定的限制,例如要求最小堆栈大小>32 KiB或要求以系统内存页面大小的倍数进行分配-应参考平台文档以获取更多信息(4 KiB页面很常见;在没有更具体信息的情况下,建议使用4096倍的堆栈大小)。Availability
: Windows, systems with POSIX threads.:Windows,带有POSIX线程的系统。
-
_thread.
TIMEOUT_MAX
¶ The maximum value allowed for the timeout parameter ofLock.acquire()
.Lock.acquire()
的timeout参数允许的最大值。Specifying a timeout greater than this value will raise an指定大于此值的超时将引发OverflowError
.OverflowError
。New in version 3.2.版本3.2中新增。
Lock objects have the following methods:锁定对象有以下方法:
-
lock.
acquire
(waitflag=1, timeout=- 1)¶ Without any optional argument, this method acquires the lock unconditionally, if necessary waiting until it is released by another thread (only one thread at a time can acquire a lock — that’s their reason for existence).在没有任何可选参数的情况下,此方法无条件地获取锁,如有必要,请等待另一个线程释放锁(一次只有一个线程可以获取锁,这就是它们存在的原因)。If the integer waitflag argument is present, the action depends on its value: if it is zero, the lock is only acquired if it can be acquired immediately without waiting, while if it is nonzero, the lock is acquired unconditionally as above.如果存在integer waitflag参数,则操作取决于其值:如果它为零,则只有在可以立即获取而不等待的情况下才能获取锁,而如果它为非零,则如上所述无条件获取锁。If the floating-point timeout argument is present and positive, it specifies the maximum wait time in seconds before returning.如果浮点timeout参数为正,则它指定返回前的最长等待时间(以秒为单位)。A negative timeout argument specifies an unbounded wait.负timeout参数指定无限制等待。You cannot specify a timeout if waitflag is zero.如果waitflag为零,则不能指定timeout。The return value is如果成功获取锁,则返回值为True
if the lock is acquired successfully,False
if not.True
,否则返回值为False
。Changed in version 3.2:版本3.2中更改:The timeout parameter is new.timeout参数是新的。Changed in version 3.2:版本3.2中更改:Lock acquires can now be interrupted by signals on POSIX.锁定获取现在可以被POSIX上的信号中断。
-
lock.
release
()¶ Releases the lock. The lock must have been acquired earlier, but not necessarily by the same thread.松开锁。锁必须是较早获取的,但不一定是由同一个线程获取的。
-
lock.
locked
()¶ Return the status of the lock:返回锁的状态:如果某个线程已经获取了锁,则返回True
if it has been acquired by some thread,False
if not.True
;如果没有,则返回False
。
In addition to these methods, lock objects can also be used via the 除了这些方法之外,还可以通过with
statement, e.g.:with
语句使用锁对象,例如:
import _thread
a_lock = _thread.allocate_lock()
with a_lock:
print("a_lock is locked while this executes")
Caveats:
Threads interact strangely with interrupts: the线程与中断的交互很奇怪:KeyboardInterrupt
exception will be received by an arbitrary thread.KeyboardInterrupt
异常将由任意线程接收。(When the(当signal
module is available, interrupts always go to the main thread.)signal
模块可用时,中断总是转到主线程。)Calling调用sys.exit()
or raising theSystemExit
exception is equivalent to calling_thread.exit()
.sys.exit()
或引发SystemExit
异常等同于调用_thread.exit()
。It is not possible to interrupt the无法中断锁上的acquire()
method on a lock — theKeyboardInterrupt
exception will happen after the lock has been acquired.acquired()
方法-KeyboardInterrupt
异常将在获取锁后发生。When the main thread exits, it is system defined whether the other threads survive.当主线程退出时,系统定义其他线程是否存活。On most systems, they are killed without executing在大多数系统上,它们在不执行try
…finally
clauses or executing object destructors.try
…finally
子句或执行对象析构函数的情况下被杀死。When the main thread exits, it does not do any of its usual cleanup (except that当主线程退出时,它不进行任何常规的清理(除了使用try
…finally
clauses are honored), and the standard I/O files are not flushed.try
…finally
子句),并且不刷新标准I/O文件。