threadingThread-based parallelism基于线程的并行性

Source code: Lib/threading.py


This module constructs higher-level threading interfaces on top of the lower level _thread module. 该模块在较低级别的_thread模块上构建较高级别的线程接口。See also the queue module.另请参见queue模块。

Changed in version 3.7:版本3.7中更改: This module used to be optional, it is now always available.这个模块过去是可选的,现在总是可用的。

Note

In the Python 2.x series, this module contained camelCase names for some methods and functions. 在Python 2x系列中,该模块包含一些方法和函数的camelCase名称。These are deprecated as of Python 3.10, but they are still supported for compatibility with Python 2.5 and lower.从Python 3.10开始,它们就被弃用了,但为了与Python 2.5及更低版本兼容,仍然支持它们。

CPython implementation detail:CPython实施细节: 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). 在CPython中,由于全局解释器锁,一次只能有一个线程执行Python代码(即使某些面向性能的库可能会克服这个限制)。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. 如果您希望应用程序更好地利用多核机器的计算资源,建议您使用multiprocessingconcurrent.futures.ProcessPoolExecutorHowever, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.然而,如果您想同时运行多个I/O绑定任务,线程仍然是合适的模型。

This module defines the following functions:本模块定义以下功能:

threading.active_count()

Return the number of Thread objects currently alive. 返回当前活动的Thread对象数。The returned count is equal to the length of the list returned by enumerate().返回的计数等于enumerate()返回的列表的长度。

The function activeCount is a deprecated alias for this function.函数activeCount是此函数的一个已弃用别名。

threading.current_thread()

Return the current Thread object, corresponding to the caller’s thread of control. 返回当前Thread对象,对应于调用方的控制线程。If the caller’s thread of control was not created through the threading module, a dummy thread object with limited functionality is returned.如果调用方的控制线程不是通过threading模块创建的,则返回功能有限的虚拟线程对象。

The function currentThread is a deprecated alias for this function.函数currentThread是此函数的一个弃用别名。

threading.excepthook(args, /)

Handle uncaught exception raised by Thread.run().处理Thread.run()引发的未捕获异常。

The args argument has the following attributes:args参数具有以下属性:

  • exc_type: Exception type.:异常类型。

  • exc_value: Exception value, can be None.:异常值,可以为None

  • exc_traceback: Exception traceback, can be None.:异常回溯,可以为None

  • thread: Thread which raised the exception, can be None.:引发异常的线程不能为None

If exc_type is SystemExit, the exception is silently ignored. 如果exc_typeSystemExit,则会自动忽略该异常。Otherwise, the exception is printed out on sys.stderr.否则,异常将打印在sys.stderr上。

If this function raises an exception, sys.excepthook() is called to handle it.如果此函数引发异常,则调用sys.excepthook()来处理它。

threading.excepthook() can be overridden to control how uncaught exceptions raised by Thread.run() are handled.可以重写以控制如何处理Thread.run()引发的未捕获异常。

Storing exc_value using a custom hook can create a reference cycle. 使用自定义挂钩存储exc_value可以创建一个引用循环。It should be cleared explicitly to break the reference cycle when the exception is no longer needed.当不再需要异常时,应明确清除该异常以中断参考循环。

Storing thread using a custom hook can resurrect it if it is set to an object which is being finalized. 如果将thread设置为正在最终确定的对象,则使用自定义挂钩存储线程可以使其恢复。Avoid storing thread after the custom hook completes to avoid resurrecting objects.避免在自定义挂钩完成后存储thread,以避免恢复对象。

See also另请参见

sys.excepthook() handles uncaught exceptions.处理未捕获的异常。

New in version 3.8.版本3.8中新增。

threading.__excepthook__

Holds the original value of threading.excepthook(). 保存threading.excepthook()的原始值。It is saved so that the original value can be restored in case they happen to get replaced with broken or alternative objects.它被保存,以便在它们碰巧被损坏或替代对象替换时可以恢复原始值。

New in version 3.10.版本3.10中新增。

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. 其价值没有直接意义;它是一种神奇的cookie,用于索引特定于线程的数据字典。Thread identifiers may be recycled when a thread exits and another thread is created.当一个线程退出并创建另一个线程时,可以回收线程标识符。

New in version 3.3.版本3.3中新增。

threading.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).其值可用于在系统范围内唯一标识该特定线程(直到线程终止,之后该值可由操作系统回收)。

Availability可利用性: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.

New in version 3.8.版本3.8中新增。

threading.enumerate()

Return a list of all Thread objects currently active. 返回当前活动的所有Thread对象的列表。The list includes daemonic threads and dummy thread objects created by current_thread(). 该列表包括daemonic线程和由current_thread()创建的虚拟线程对象。It excludes terminated threads and threads that have not yet been started. 它不包括终止的线程和尚未启动的线程。However, the main thread is always part of the result, even when terminated.然而,主线程始终是结果的一部分,即使在终止时也是如此。

threading.main_thread()

Return the main Thread object. 返回主Thread对象。In normal conditions, the main thread is the thread from which the Python interpreter was started.在正常情况下,主线程是启动Python解释器的线程。

New in version 3.4.版本3.4中新增。

threading.settrace(func)

Set a trace function for all threads started from the threading module. 为从threading模块启动的所有线程设置跟踪函数。The func will be passed to sys.settrace() for each thread, before its run() method is called.在调用其run()方法之前,func将传递给每个线程的sys.settrace()

threading.gettrace()

Get the trace function as set by settrace().获取settrace()设置的跟踪函数。

New in version 3.10.版本3.10中新增。

threading.setprofile(func)

Set a profile function for all threads started from the threading module. 为从threading模块开始的所有线程设置配置文件函数。The func will be passed to sys.setprofile() for each thread, before its run() method is called.在调用其run()方法之前,func将传递给每个线程的sys.setprofile()

threading.getprofile()

Get the profiler function as set by setprofile().获取由setprofile()设置的探查器函数。

New in version 3.10.版本3.10中新增。

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). 可选的size参数指定用于后续创建的线程的堆栈大小,并且必须为0(使用平台或配置的默认值)或至少32768(32 KiB)的正整数值。If size is not specified, 0 is used. 如果未指定size,则使用0。If changing the thread stack size is unsupported, a RuntimeError is raised. 如果不支持更改线程堆栈大小,则会引发RuntimeErrorIf the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 如果指定的堆栈大小无效,则会引发ValueError,并且不会修改堆栈大小。32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. 32 KiB是当前支持的最小堆栈大小值,以保证解释器本身有足够的堆栈空间。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线程的系统。

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.). 阻塞函数(Lock.acquire()RLock.acquire()Condition.wait()等)的超时参数允许的最大值。Specifying a timeout greater than this value will raise an OverflowError.指定大于此值的超时将引发OverflowError

New in version 3.2.版本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. 该模块的设计松散地基于Java的线程模型。However, where Java makes locks and condition variables basic behavior of every object, they are separate objects in Python. 然而,当Java使锁和条件变量成为每个对象的基本行为时,它们在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. Python的Thread类支持Java线程类行为的子集;目前,没有优先级,没有线程组,线程不能被销毁、停止、挂起、恢复或中断。The static methods of Java’s Thread class, when implemented, are mapped to module-level functions.Java线程类的静态方法在实现时映射到模块级函数。

All of the methods described below are executed atomically.下面描述的所有方法都是原子执行的。

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:要管理线程本地数据,只需创建local(或子类)的实例并在其上存储属性:

mydata = threading.local()
mydata.x = 1

The instance’s values will be different for separate threads.对于不同的线程,实例的值将不同。

classthreading.local

A class that represents thread-local data.表示线程本地数据的类。

For more details and extensive examples, see the documentation string of the _threading_local module.有关更多详细信息和广泛示例,请参阅_threading_local模块的文档字符串。

Thread Objects对象

The Thread class represents an activity that is run in a separate thread of control. Thread类表示在单独的控制线程中运行的活动。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. 指定活动有两种方法:将可调用对象传递给构造函数,或重写子类中的run()方法。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.换句话说,只重写此类的__init__()run()方法。

Once a thread object is created, its activity must be started by calling the thread’s start() method. 创建线程对象后,必须通过调用线程的start()方法来启动其活动。This invokes the run() method in a separate thread of control.这将在单独的控制线程中调用run()方法。

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. 当其run()方法终止时,它停止活动-正常终止或引发未处理的异常。The is_alive() method tests whether the thread is alive.is_alive()方法测试线程是否处于活动状态。

Other threads can call a thread’s join() method. 其他线程可以调用线程的join()方法。This blocks the calling thread until the thread whose join() method is called is terminated.这会阻止调用线程,直到其join()方法被调用的线程终止。

A thread has a name. 线程有一个名称。The name can be passed to the constructor, and read or changed through the name attribute.可以将名称传递给构造函数,并通过name属性读取或更改。

If the run() method raises an exception, threading.excepthook() is called to handle it. 如果run()方法引发异常,则会调用threading.excepthook()来处理它。By default, threading.excepthook() ignores silently SystemExit.默认情况下,threading.excepthook()自动忽略SystemExit

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. 这个标志的意义在于,当只剩下守护进程线程时,整个Python程序就会退出。The initial value is inherited from the creating thread. 初始值继承自创建线程。The flag can be set through the daemon property or the daemon constructor argument.该标志可以通过daemon属性或daemon构造函数参数设置。

Note笔记

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.如果希望线程正常停止,请将其设为非守护线程,并使用适当的信号机制,如Event

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. 有一个“主线”对象;这对应于Python程序中的初始控制线程。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. 这些是对应于“外来线程”的线程对象,这些线程是在线程模块外部启动的控制线程,例如直接从C代码启动。Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. 虚拟线程对象的功能有限;它们总是被认为是活动的和守护的,不能被join()They are never deleted, since it is impossible to detect the termination of alien threads.它们永远不会被删除,因为不可能检测到外来线程的终止。

classthreading.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 a ThreadGroup class is implemented.应为None;保留供将来实现ThreadGroup类时扩展。

target is the callable object to be invoked by the run() method. run()方法调用的可调用对象。Defaults to None, meaning nothing is called.默认为None,表示不调用任何内容。

name is the thread name. 是线程名称。By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number, or “Thread-N (target)” where “target” is target.__name__ if the target argument is specified.默认情况下,唯一名称的构造形式为“Thread-N”,其中N是一个小的十进制数,或“Thread-N(target)”,其中“target”是target.__name__如果指定了target参数。

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. 如果不是Nonedaemon将显式设置线程是否为守护进程。If None (the default), the daemonic property is inherited from the current thread.如果为None(默认),则daemonic属性从当前线程继承。

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.如果子类重写构造函数,则必须确保在对线程执行任何其他操作之前调用基类构造函数(Thread.__init__())。

Changed in version 3.10:版本3.10中更改: Use the target name if name argument is omitted.如果省略name参数,请使用target名称。

Changed in version 3.3:版本3.3中更改: Added the daemon argument.添加了daemon参数。

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.它安排在单独的控制线程中调用对象的run()方法。

This method will raise a RuntimeError if called more than once on the same thread object.如果在同一个线程对象上调用多次,此方法将引发RuntimeError

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 positional and keyword arguments taken from the args and kwargs arguments, respectively.标准run()方法调用传递给对象构造函数的可调用对象作为target参数(如果有),位置参数和关键字参数分别取自argskwargs参数。

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.这会阻止调用线程,直到调用其join()方法的线程终止(正常终止或通过未处理的异常终止),或者直到出现可选超时。

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). timeout参数存在而不是None时,它应该是一个浮点数,以秒(或其分数)为单位指定操作超时。As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.由于join()总是返回None,因此必须在join()之后调用is_alive(),以确定是否发生超时-如果线程仍处于活动状态,则join()调用超时。

When the timeout argument is not present or None, the operation will block until the thread terminates.timeout参数不存在或为None时,操作将阻塞,直到线程终止。

A thread can be join()ed many times.一个线程可以被多次join()

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. 如果试图加入当前线程,join()会引发RuntimeError,因为这会导致死锁。It is also an error to join() a thread before it has been started and attempts to do so raise the same exception.在线程启动之前join()也是一个错误,尝试这样做会引发相同的异常。

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.初始名称由构造函数设置。

getName()
setName()

Deprecated getter/setter API for name; use it directly as a property instead.name的getter/setter API已弃用;直接将其用作属性。

Deprecated since version 3.10.自版本3.10以来已弃用。

ident

The ‘thread identifier’ of this thread or None if the thread has not been started. 此线程的“线程标识符”,如果线程尚未启动,则为NoneThis is a nonzero integer. 这是一个非零整数。See the get_ident() function. 请参阅get_ident()函数。Thread identifiers may be recycled when a thread exits and another thread is created. 当一个线程退出并创建另一个线程时,可以回收线程标识符。The identifier is available even after the thread has exited.即使在线程退出后,该标识符仍然可用。

native_id

The Thread ID (TID) of this thread, as assigned by the OS (kernel). 此线程的线程ID(TID),由操作系统(内核)分配。This is a non-negative integer, or None if the thread has not been started. 这是一个非负整数,如果线程尚未启动,则为NoneSee the get_native_id() function. 请参阅get_native_id()函数。This 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).该值可用于在系统范围内唯一标识该特定线程(直到线程终止,之后该值可由操作系统回收)。

Note

Similar to Process IDs, Thread IDs are only valid (guaranteed unique system-wide) from the time the thread is created until the thread has been terminated.与进程ID类似,线程ID仅在创建线程到终止线程期间有效(保证系统范围内唯一)。

Availability可用性: Requires get_native_id() function.:需要get_native_id()函数。

New in version 3.8.版本3.8中新增。

is_alive()

Return whether the thread is alive.返回线程是否处于活动状态。

This method returns True just before the run() method starts until just after the run() method terminates. 该方法在run()方法开始之前返回True,直到run()方法终止之后。The module function enumerate() returns a list of all alive threads.模块函数enumerate()返回所有活动线程的列表。

daemon

A boolean value indicating whether this thread is a daemon thread (True) or not (False). 一个布尔值,指示此线程是否为守护进程线程(True)或(False)。This must be set before start() is called, otherwise RuntimeError is raised. 这必须在调用start()之前设置,否则会引发RuntimeErrorIts 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 to daemon = False.其初始值继承自创建线程;主线程不是守护进程线程,因此在主线程中创建的所有线程默认为daemon=False

The entire Python program exits when no alive non-daemon threads are left.当没有活动的非守护进程线程时,整个Python程序退出。

isDaemon()
setDaemon()

Deprecated getter/setter API for daemon; use it directly as a property instead.daemon的getter/setter API已弃用;直接将其用作属性。

Deprecated since version 3.10.自版本3.10以来已弃用。

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.在Python中,它是当前可用的最低级别的同步原语,由_thread扩展模块直接实现。

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(). 它有两个基本方法,<acquire()release()When the state is unlocked, acquire() changes the state to locked and returns immediately. 当状态处于解锁状态时,acquire()将状态更改为锁定并立即返回。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. 当状态被锁定时,acquire()阻塞,直到另一个线程中对release()的调用将其更改为unlocked,然后acquire()调用将其重置为locked并返回。The release() method should only be called in the locked state; it changes the state to unlocked and returns immediately. release()方法只能在锁定状态下调用;它将状态更改为unlocked并立即返回。If an attempt is made to release an unlocked lock, a RuntimeError will be raised.如果试图释放未锁定的锁,则会引发RuntimeError

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.当多个线程在acquire()中被阻塞,等待状态变为unlocked时,当release()调用将状态重置为unlocked时,只有一个线程继续;等待线程中的哪一个尚未定义,可能因实现而异。

All methods are executed atomically.所有方法都是原子执行的。

classthreading.Lock

The class implementing primitive lock objects. 实现基元锁对象的类。Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it.一旦一个线程获得了一个锁,随后获取它的尝试就会被阻止,直到它被释放;任何线程都可以释放它。

Note that Lock is actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform.请注意,Lock实际上是一个工厂函数,它返回平台支持的最有效的具体锁类版本的实例。

acquire(blocking=True, timeout=- 1)

Acquire a lock, blocking or non-blocking.获取锁,阻塞或非阻塞。

When invoked with the blocking argument set to True (the default), block until the lock is unlocked, then set it to locked and return True.当在blocking参数设置为True(默认值)的情况下调用时,阻塞直到锁解锁,然后将其设置为locked并返回True

When invoked with the blocking argument set to False, do not block. 当在blocking参数设置为False的情况下调用时,不要阻塞。If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True.如果blocking设置为True的调用将阻塞,则立即返回False;否则,将锁设置为locked并返回True

When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. 当在浮点timeout参数设置为正值的情况下调用时,只要无法获取锁,则阻塞时间最多为timeout指定的秒数。A timeout argument of -1 specifies an unbounded wait. timeout参数-1指定无限等待。It is forbidden to specify a timeout when blocking is False.blockingFalse时,禁止指定timeout

The return value is True if the lock is acquired successfully, False if not (for example if the timeout expired).如果成功获取锁,则返回值为True,否则返回值为False(例如,如果timeout已过期)。

Changed in version 3.2:版本3.2中更改: The timeout parameter is new.timeout参数是新的。

Changed in version 3.2:版本3.2中更改: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it.如果底层线程实现支持,则POSIX上的信号现在可以中断锁获取。

release()

Release a lock. 释放锁。This can be called from any thread, not only the thread which has acquired the lock.这可以从任何线程调用,而不仅仅是获取锁的线程。

When the lock is locked, reset it to unlocked, and return. 锁定后,将其重置为解锁,然后返回。If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed.如果任何其他线程被阻塞,等待锁解锁,则只允许其中一个线程继续。

When invoked on an unlocked lock, a RuntimeError is raised.在解锁的锁上调用时,会引发RuntimeError

There is no return value.没有返回值。

locked()

Return True if the lock is acquired.如果获取了锁,则返回True

RLock Objects对象

A reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread. 可重入锁是一种同步原语,可由同一线程多次获取。Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. 在内部,除了原语锁使用的锁定/解锁状态外,它还使用了“拥有线程”和“递归级别”的概念。In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.在锁定状态下,某些线程拥有锁;在解锁状态下,没有线程拥有它。

To lock the lock, a thread calls its acquire() method; this returns once the thread owns the lock. 为了锁定锁,线程调用其acquire()方法;一旦线程拥有锁,就会返回。To unlock the lock, a thread calls its release() method. 为了解锁锁,线程调用其release()方法。acquire()/release() call pairs may be nested; only the final release() (the release() of the outermost pair) resets the lock to unlocked and allows another thread blocked in acquire() to proceed.可以嵌套acquire()/release()调用对;只有最后的release()(最外层对的release())将锁重置为解锁,并允许在acquire()中阻塞的另一个线程继续。

Reentrant locks also support the context management protocol.可重入锁还支持上下文管理协议

classthreading.RLock

This class implements reentrant lock objects. 此类实现可重入的锁对象。A reentrant lock must be released by the thread that acquired it. 可重入锁必须由获取它的线程释放。Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.一旦一个线程获得了可重入锁,同一个线程就可以在不阻塞的情况下再次获得它;线程每次获取它时必须释放它一次。

Note that RLock is actually a factory function which returns an instance of the most efficient version of the concrete RLock class that is supported by the platform.请注意,RLock实际上是一个工厂函数,它返回平台支持的具体RLock类的最有效版本的实例。

acquire(blocking=True, timeout=- 1)

Acquire a lock, blocking or non-blocking.获取锁,阻塞或非阻塞。

When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. 当在没有参数的情况下调用时:如果该线程已经拥有锁,则将递归级别增加一,然后立即返回。Otherwise, if another thread owns the lock, block until the lock is unlocked. 否则,如果另一个线程拥有该锁,则阻塞直到该锁解锁。Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. 一旦锁被解锁(不属于任何线程),那么获取所有权,将递归级别设置为1,然后返回。If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. 如果有多个线程被阻塞,等待锁解锁,那么一次只能有一个线程能够获取锁的所有权。There is no return value in this case.在这种情况下没有返回值。

When invoked with the blocking argument set to True, do the same thing as when called without arguments, and return True.当在blocking参数设置为True的情况下调用时,执行与在没有参数的情况下调用时相同的操作,并返回True

When invoked with the blocking argument set to False, do not block. 当在blocking参数设置为False的情况下调用时,不要阻塞。If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True.如果没有参数的调用将阻塞,则立即返回False;否则,执行与无参数调用时相同的操作,并返回True

When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. 当在浮点timeout参数设置为正值的情况下调用时,只要无法获取锁,则阻塞时间最多为超时指定的秒数。Return True if the lock has been acquired, False if the timeout has elapsed.如果已获取锁,则返回True;如果超时已过,则返回False

Changed in version 3.2:版本3.2中更改: The timeout parameter is new.timeout参数是新的。

release()

Release a lock, decrementing the recursion level. 释放锁,降低递归级别。If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. 如果减量后为零,则将锁重置为unlocked(不属于任何线程),如果任何其他线程被阻塞,等待锁解锁,则只允许其中一个线程继续。If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread.如果递减后递归级别仍然非零,则锁仍被锁定并由调用线程拥有。

Only call this method when the calling thread owns the lock. 仅当调用线程拥有锁时才调用此方法。A RuntimeError is raised if this method is called when the lock is unlocked.如果在锁解锁时调用此方法,则会引发RuntimeError

There is no return value.没有返回值。

Condition Objects对象

A condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. 条件变量总是与某种锁相关联;这可以传入,也可以默认创建一个。Passing one in is useful when several condition variables must share the same lock. 当多个条件变量必须共享同一个锁时,传入一个是有用的。The lock is part of the condition object: you don’t have to track it separately.锁是条件对象的一部分:您不必单独跟踪它。

A condition variable obeys the context management protocol: using the with statement acquires the associated lock for the duration of the enclosed block. 条件变量遵循上下文管理协议:使用with语句在封闭块的持续时间内获取相关锁。The acquire() and release() methods also call the corresponding methods of the associated lock.acquire()release()方法还调用关联锁的相应方法。

Other methods must be called with the associated lock held. 必须在保持相关锁的情况下调用其他方法。The wait() method releases the lock, and then blocks until another thread awakens it by calling notify() or notify_all(). wait()方法释放锁,然后阻塞,直到另一个线程通过调用notify()notify_all()将其唤醒。Once awakened, wait() re-acquires the lock and returns. 唤醒后,wait()重新获取锁并返回。It is also possible to specify a timeout.也可以指定超时。

The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. notify()方法唤醒等待条件变量的线程之一(如果有)。The notify_all() method wakes up all threads waiting for the condition variable.notify_all()方法唤醒所有等待条件变量的线程。

Note: the notify() and notify_all() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notify_all() finally relinquishes ownership of the lock.注意:notify()notify_all()方法不会释放锁;这意味着被唤醒的一个或多个线程不会立即从其wait()调用返回,而只有在调用notify()notify_all()的线程最终放弃锁的所有权时才会返回。

The typical programming style using condition variables uses the lock to synchronize access to some shared state; threads that are interested in a particular change of state call wait() repeatedly until they see the desired state, while threads that modify the state call notify() or notify_all() when they change the state in such a way that it could possibly be a desired state for one of the waiters. 使用条件变量的典型编程风格使用锁来同步对某些共享状态的访问;对状态调用的特定更改感兴趣的线程会反复wait(),直到看到所需的状态,而修改状态调用notify()notify_all()的线程在更改状态时可能是其中一个等待者所需的状态。For example, the following code is a generic producer-consumer situation with unlimited buffer capacity:例如,以下代码是具有无限缓冲容量的一般生产者-消费者情况:

# Consume one item
with cv:
while not an_item_is_available():
cv.wait()
get_an_available_item()
# Produce one item
with cv:
make_an_item_available()
cv.notify()

The while loop checking for the application’s condition is necessary because wait() can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true. 对应用程序条件进行while循环检查是必要的,因为wait()可以在任意长时间后返回,并且提示notify()调用的条件可能不再成立。This is inherent to multi-threaded programming. 这是多线程编程固有的。The wait_for() method can be used to automate the condition checking, and eases the computation of timeouts:wait_for()方法可用于自动进行条件检查,并简化超时的计算:

# Consume an item
with cv:
cv.wait_for(an_item_is_available)
get_an_available_item()

To choose between notify() and notify_all(), consider whether one state change can be interesting for only one or several waiting threads. 要在notify()notify_all()之间进行选择,请考虑一个状态更改是否仅对一个或多个等待的线程有意义。E.g. in a typical producer-consumer situation, adding one item to the buffer only needs to wake up one consumer thread.在典型的生产者-消费者情况下,向缓冲区添加一个项目只需要唤醒一个消费者线程。

classthreading.Condition(lock=None)

This class implements condition variable objects. 此类实现了条件变量对象。A condition variable allows one or more threads to wait until they are notified by another thread.条件变量允许一个或多个线程等待,直到收到另一个线程的通知。

If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. 如果给定了lock参数而不是None,则它必须是LockRLock对象,并用作基础锁。Otherwise, a new RLock object is created and used as the underlying lock.否则,将创建一个新的RLock对象并将其用作基础锁。

Changed in version 3.3:版本3.3中更改: changed from a factory function to a class.从工厂函数更改为类。

acquire(*args)

Acquire the underlying lock. 获取基础锁。This method calls the corresponding method on the underlying lock; the return value is whatever that method returns.该方法调用底层锁上的相应方法;返回值是该方法返回的任何值。

release()

Release the underlying lock. 释放底层锁。This method calls the corresponding method on the underlying lock; there is no return value.该方法调用底层锁上的相应方法;没有返回值。

wait(timeout=None)

Wait until notified or until a timeout occurs. 等待,直到收到通知或发生超时。If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.如果调用此方法时调用线程尚未获取锁,则会引发RuntimeError

This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. 这个方法释放底层锁,然后阻塞,直到它被另一个线程中相同条件变量的notify()notify_all()调用唤醒,或者直到出现可选超时。Once awakened or timed out, it re-acquires the lock and returns.一旦唤醒或超时,它将重新获取锁并返回。

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).timeout参数存在而不是None时,它应该是一个浮点数,以秒(或其分数)为单位指定操作超时。

When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. 当底层锁是RLock时,不会使用其release()方法释放它,因为这实际上可能不会在多次递归获取锁时解锁它。Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. 相反,使用了RLock类的内部接口,即使递归获取了多次,也可以真正解锁它。Another internal interface is then used to restore the recursion level when the lock is reacquired.然后,在重新获取锁时,使用另一个内部接口来恢复递归级别。

The return value is True unless a given timeout expired, in which case it is False.除非给定超时过期,否则返回值为True,在这种情况下,返回值为False

Changed in version 3.2:版本3.2中更改: Previously, the method always returned None.以前,该方法总是返回None

wait_for(predicate, timeout=None)

Wait until a condition evaluates to true. 等待条件评估为truepredicate should be a callable which result will be interpreted as a boolean value. predicate应该是可调用的,其结果将被解释为布尔值。A timeout may be provided giving the maximum time to wait.可以提供一个timeout,以提供最长的等待时间。

This utility method may call wait() repeatedly until the predicate is satisfied, or until a timeout occurs. 此实用程序方法可以重复调用wait(),直到满足谓词,或者直到发生超时。The return value is the last return value of the predicate and will evaluate to False if the method timed out.返回值是谓词的最后一个返回值,如果方法超时,返回值将计算为False

Ignoring the timeout feature, calling this method is roughly equivalent to writing:忽略超时功能,调用此方法大致相当于写入:

while not predicate():
cv.wait()

Therefore, the same rules apply as with wait(): The lock must be held when called and is re-acquired on return. 因此,应用与wait()相同的规则:调用时必须持有锁,并在返回时重新获取。The predicate is evaluated with the lock held.谓词在保持锁的情况下求值。

New in version 3.2.版本3.2中新增。

notify(n=1)

By default, wake up one thread waiting on this condition, if any. 默认情况下,唤醒一个在此条件下等待的线程(如果有)。If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.如果调用此方法时调用线程尚未获取锁,则会引发RuntimeError

This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting.该方法最多唤醒n个等待条件变量的线程;如果没有线程等待,则为无操作。

The current implementation wakes up exactly n threads, if at least n threads are waiting. 如果至少有n个线程正在等待,则当前实现将唤醒n个线程。However, it’s not safe to rely on this behavior. 然而,依赖这种行为是不安全的。A future, optimized implementation may occasionally wake up more than n threads.未来的优化实现可能偶尔会唤醒超过n个线程。

Note: an awakened thread does not actually return from its wait() call until it can reacquire the lock. 注意:唤醒的线程实际上不会从其wait()调用返回,直到它可以重新获取锁。Since notify() does not release the lock, its caller should.由于notify()不会释放锁,因此其调用程序应该。

notify_all()

Wake up all threads waiting on this condition. 唤醒在此条件下等待的所有线程。This method acts like notify(), but wakes up all waiting threads instead of one. 此方法的作用类似于notify(),但会唤醒所有等待的线程,而不是一个线程。If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.如果调用此方法时调用线程尚未获取锁,则会引发RuntimeError

The method notifyAll is a deprecated alias for this method.notifyAll方法是此方法的一个已弃用别名。

Semaphore Objects对象

This is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used the names P() and V() instead of acquire() and release()).这是计算机科学史上最古老的同步原语之一,由早期荷兰计算机科学家Edsger W.Dijkstra发明(他使用了P()V()的名称,而不是acquire()release()

A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. 信号量管理一个内部计数器,该计数器由每个acquire()调用递减,由每个release()调用递增。The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release().计数器永远不能低于零;当acquire()发现它为零时,它会阻塞,直到其他线程调用release()

Semaphores also support the context management protocol.信号量还支持上下文管理协议

classthreading.Semaphore(value=1)

This class implements semaphore objects. 此类实现信号量对象。A semaphore manages an atomic counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. 信号量管理一个原子计数器,表示release()调用的数量减去acquire()调用的数量,再加上一个初始值。The acquire() method blocks if necessary until it can return without making the counter negative. 如果需要,acquire()方法会阻塞,直到可以返回而不使计数器为负。If not given, value defaults to 1.如果未给定,则value默认为1。

The optional argument gives the initial value for the internal counter; it defaults to 1. 可选参数给出内部计数器的初始value;默认为1If the value given is less than 0, ValueError is raised.如果给定的value小于0,则会引发ValueError

Changed in version 3.3:版本3.3中更改: changed from a factory function to a class.从工厂函数更改为类。

acquire(blocking=True, timeout=None)

Acquire a semaphore.获取信号量。

When invoked without arguments:在没有参数的情况下调用时:

  • If the internal counter is larger than zero on entry, decrement it by one and return True immediately.如果输入时内部计数器大于零,则将其减1,并立即返回True

  • If the internal counter is zero on entry, block until awoken by a call to release(). 如果输入时内部计数器为零,则阻塞,直到调用release()将其唤醒。Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. 一旦唤醒(计数器大于0),将计数器减量1并返回TrueExactly one thread will be awoken by each call to release(). 每次调用release()都会唤醒一个线程。The order in which threads are awoken should not be relied on.不应依赖线程的唤醒顺序。

When invoked with blocking set to False, do not block. blocking设置为False时调用时,不要阻塞。If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True.如果没有参数的调用将阻塞,则立即返回False;否则,执行与无参数调用时相同的操作,并返回True

When invoked with a timeout other than None, it will block for at most timeout seconds. 当在非None超时的情况下调用时,它最多会阻塞timeout秒。If acquire does not complete successfully in that interval, return False. 如果在该间隔内未成功完成获取,则返回FalseReturn True otherwise.否则返回True

Changed in version 3.2:版本3.2中更改: The timeout parameter is new.timeout参数是新的。

release(n=1)

Release a semaphore, incrementing the internal counter by n. 释放信号量,将内部计数器增加nWhen it was zero on entry and other threads are waiting for it to become larger than zero again, wake up n of those threads.当它在条目上为零时,其他线程正在等待它再次大于零,请唤醒其中的n个线程。

Changed in version 3.9:版本3.9中更改: Added the n parameter to release multiple waiting threads at once.添加了n参数以一次释放多个等待线程。

classthreading.BoundedSemaphore(value=1)

Class implementing bounded semaphore objects. 实现有界信号量对象的类。A bounded semaphore checks to make sure its current value doesn’t exceed its initial value. 有界信号量检查以确保其当前值不超过其初始值。If it does, ValueError is raised. 如果是,则会引发ValueErrorIn most situations semaphores are used to guard resources with limited capacity. 在大多数情况下,信号量用于保护容量有限的资源。If the semaphore is released too many times it’s a sign of a bug. 如果信号量被释放太多次,则表明存在错误。If not given, value defaults to 1.如果未给定,则value默认为1。

Changed in version 3.3:版本3.3中更改: changed from a factory function to a class.从工厂函数更改为类。

Semaphore Example示例

Semaphores are often used to guard resources with limited capacity, for example, a database server. 信号量通常用于保护容量有限的资源,例如数据库服务器。In any situation where the size of the resource is fixed, you should use a bounded semaphore. 在资源大小固定的任何情况下,都应该使用有界信号量。Before spawning any worker threads, your main thread would initialize the semaphore:在生成任何工作线程之前,主线程将初始化信号量:

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)

Once spawned, worker threads call the semaphore’s acquire and release methods when they need to connect to the server:生成后,工作线程在需要连接到服务器时调用信号量的获取和释放方法:

with pool_sema:
conn = connectdb()
try:
# ... use connection ...
finally:
conn.close()

The use of a bounded semaphore reduces the chance that a programming error which causes the semaphore to be released more than it’s acquired will go undetected.使用有界信号量可以减少编程错误(导致信号量的释放量超过其获取量)未被检测到的可能性。

Event Objects对象

This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.这是线程间通信的最简单机制之一:一个线程发出事件信号,其他线程等待。

An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. 事件对象管理一个内部标志,该标志可以用set()方法设置为true,用clear()方法重置为falseThe wait() method blocks until the flag is true.wait()方法阻塞,直到标志为true

classthreading.Event

Class implementing event objects. 实现事件对象的类。An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. 事件管理一个标志,该标志可以用set()方法设置为true,用clear()方法重置为falseThe wait() method blocks until the flag is true. wait()方法阻塞,直到标志为trueThe flag is initially false.标志最初为false

Changed in version 3.3:版本3.3中更改: changed from a factory function to a class.从工厂函数更改为类。

is_set()

Return True if and only if the internal flag is true.当且仅当内部标志为True时返回True

The method isSet is a deprecated alias for this method.方法isSet是此方法的一个已弃用别名。

set()

Set the internal flag to true. 将内部标志设置为trueAll threads waiting for it to become true are awakened. 所有等待它实现的线程都被唤醒。Threads that call wait() once the flag is true will not block at all.一旦标志为true,调用wait()的线程将根本不会阻塞。

clear()

Reset the internal flag to false. 将内部标志重置为falseSubsequently, threads calling wait() will block until set() is called to set the internal flag to true again.随后,调用wait()的线程将阻塞,直到调用set()将内部标志再次设置为true

wait(timeout=None)

Block until the internal flag is true. If the internal flag is true on entry, return immediately. 阻止,直到内部标志为true。如果输入时内部标志为true,则立即返回。Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.否则,阻塞,直到另一个线程调用set()将标志设置为true,或者直到出现可选超时。

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).timeout参数存在而不是None时,它应该是一个浮点数,以秒(或其分数)为单位指定操作超时。

This method returns True if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return True except if a timeout is given and the operation times out.当且仅当内部标志在等待调用之前或等待开始之后设置为True时,此方法才返回True,因此除非给定超时且操作超时,否则它将始终返回True

Changed in version 3.1:版本3.1中更改: Previously, the method always returned None.以前,该方法总是返回None

Timer Objects对象

This class represents an action that should be run only after a certain amount of time has passed — a timer. 此类表示一个操作,该操作应仅在经过一定时间后运行-计时器。Timer is a subclass of Thread and as such also functions as an example of creating custom threads.TimerThread的一个子类,因此也可以作为创建自定义线程的示例。

Timers are started, as with threads, by calling their start() method. 与线程一样,计时器是通过调用其start()方法启动的。The timer can be stopped (before its action has begun) by calling the cancel() method. 可以通过调用cancel()方法停止计时器(在其操作开始之前)。The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.计时器在执行其操作之前等待的间隔可能与用户指定的间隔不完全相同。

For example:例如:

def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
classthreading.Timer(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. 创建一个计时器,该计时器将在interval秒后运行带有参数args和关键字参数kwargsfunctionIf args is None (the default) then an empty list will be used. 如果argsNone(默认值),则将使用空列表。If kwargs is None (the default) then an empty dict will be used.如果kwargsNone(默认值),则将使用空dict。

Changed in version 3.3:版本3.3中更改: changed from a factory function to a class.从工厂函数更改为类。

cancel()

Stop the timer, and cancel the execution of the timer’s action. 停止计时器,并取消计时器动作的执行。This will only work if the timer is still in its waiting stage.只有当计时器仍处于等待阶段时,这才有效。

Barrier Objects对象

New in version 3.2.版本3.2中新增。

This class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other. 此类提供了一个简单的同步原语,供需要相互等待的固定数量的线程使用。Each of the threads tries to pass the barrier by calling the wait() method and will block until all of the threads have made their wait() calls. 每个线程都试图通过调用wait()方法来通过障碍,并将阻塞,直到所有线程都进行了wait()调用。At this point, the threads are released simultaneously.此时,线程将同时释放。

The barrier can be reused any number of times for the same number of threads.对于相同数量的线程,屏障可以重复使用任意次数。

As an example, here is a simple way to synchronize a client and server thread:例如,以下是同步客户端和服务器线程的简单方法:

b = Barrier(2, timeout=5)
def server():
start_server()
b.wait()
while True:
connection = accept_connection()
process_server_connection(connection)

def client():
b.wait()
while True:
connection = make_connection()
process_client_connection(connection)
classthreading.Barrier(parties, action=None, timeout=None)

Create a barrier object for parties number of threads. 为线程parties数创建障碍对象。An action, when provided, is a callable to be called by one of the threads when they are released. 如果提供了action,则可以在其中一个线程被释放时调用该操作。timeout is the default timeout value if none is specified for the wait() method.如果未为wait()方法指定任何超时值,则timeout是默认超时值。

wait(timeout=None)

Pass the barrier. 通过障碍。When all the threads party to the barrier have called this function, they are all released simultaneously. 当障碍的所有线程都调用此函数时,它们都会同时释放。If a timeout is provided, it is used in preference to any that was supplied to the class constructor.如果提供了timeout,则它将优先于提供给类构造函数的任何超时。

The return value is an integer in the range 0 to parties – 1, different for each thread. 返回值是一个范围为0到parties-1的整数,每个线程的返回值不同。This can be used to select a thread to do some special housekeeping, e.g.:这可以用来选择一个线程来执行一些特殊的内务处理,例如:

i = barrier.wait()
if i == 0:
# Only one thread needs to print this
print("passed the barrier")

If an action was provided to the constructor, one of the threads will have called it prior to being released. 如果向构造函数提供了一个action,那么其中一个线程将在发布之前调用它。Should this call raise an error, the barrier is put into the broken state.如果此调用引发错误,则屏障将处于断开状态。

If the call times out, the barrier is put into the broken state.如果呼叫超时,屏障将处于断开状态。

This method may raise a BrokenBarrierError exception if the barrier is broken or reset while a thread is waiting.如果在线程等待时屏障被破坏或重置,此方法可能会引发BrokenBarrierError异常。

reset()

Return the barrier to the default, empty state. 将屏障恢复为默认的空状态。Any threads waiting on it will receive the BrokenBarrierError exception.等待它的任何线程都将收到BrokenBarrierError异常。

Note that using this function may require some external synchronization if there are other threads whose state is unknown. 请注意,如果有其他状态未知的线程,则使用此函数可能需要一些外部同步。If a barrier is broken it may be better to just leave it and create a new one.如果一个障碍被打破了,最好离开它,创建一个新的障碍。

abort()

Put the barrier into a broken state. 将障碍物置于破损状态。This causes any active or future calls to wait() to fail with the BrokenBarrierError. 这会导致任何活动的或将来的调用wait()失败,并出现BrokenBarrierErrorUse this for example if one of the threads needs to abort, to avoid deadlocking the application.例如,如果其中一个线程需要中止,请使用此选项,以避免应用程序死锁。

It may be preferable to simply create the barrier with a sensible timeout value to automatically guard against one of the threads going awry.最好是简单地创建具有合理timeout值的屏障,以自动防止其中一个线程出错。

parties

The number of threads required to pass the barrier.通过屏障所需的螺纹数。

n_waiting

The number of threads currently waiting in the barrier.当前在屏障中等待的线程数。

broken

A boolean that is True if the barrier is in the broken state.如果屏障处于断开状态,则为True的布尔值。

exceptionthreading.BrokenBarrierError

This exception, a subclass of RuntimeError, is raised when the Barrier object is reset or broken.此异常是RuntimeError的一个子类,在重置或破坏Barrier对象时引发。

Using locks, conditions, and semaphores in the with statementwith语句中使用锁、条件和信号量

All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement. 该模块提供的所有具有acquire()release()方法的对象都可以用作with语句的上下文管理器。The acquire() method will be called when the block is entered, and release() will be called when the block is exited. 输入块时将调用acquire()方法,退出块时将调用release()Hence, the following snippet:因此,以下代码段:

with some_lock:
# do something...

is equivalent to:相当于:

some_lock.acquire()
try:
# do something...
finally:
some_lock.release()

Currently, Lock, RLock, Condition, Semaphore, and BoundedSemaphore objects may be used as with statement context managers.目前,LockRLockConditionSemaphoreBoundedSemaphore对象可以与语句上下文管理器一起使用。