threading
--- 基于线程的并发¶
源代码: Lib/threading.py
这个模块在较低级的模块 _thread
基础上建立较高级的线程接口。参见: queue
模块。
在 3.7 版更改: 这个模块曾经为可选项,但现在总是可用。
注解
虽然他们没有在下面列出,这个模块仍然支持Python 2.x系列的这个模块下以 camelCase
(驼峰法)命名的方法和函数。
这个模块定义了以下函数:
-
threading.
active_count
()¶ 返回当前存活的线程类
Thread
对象。返回的计数等于enumerate()
返回的列表长度。
-
threading.
get_ident
()¶ 返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义,主要是用作 magic cookie,比如作为含有线程相关数据的字典的索引。线程标识符可能会在线程退出,新线程创建时被复用。
3.3 新版功能.
-
threading.
enumerate
()¶ 以列表形式返回当前所有存活的
Thread
对象。该列表包含守护线程,current_thread()
创建的虚拟线程对象和主线程。它包含了已终结的线程和尚未开始的线程。
-
threading.
settrace
(func)¶ 为所有
threading
模块开始的线程设置追踪函数。在每个线程的run()
方法被调用前,func 会被传递给sys.settrace()
。
-
threading.
setprofile
(func)¶ 为所有
threading
模块开始的线程设置性能测试函数。在每个线程的run()
方法被调用前,func 会被传递给sys.setprofile()
。
-
threading.
stack_size
([size])¶ 返回创建线程时用的堆栈大小。可选参数 size 指定之后新建的线程的堆栈大小,而且一定要是0(根据平台或者默认配置)或者最小是32,768(32KiB)的一个正整数。如果 size 没有指定,默认是0。如果不支持改变线程堆栈大小,会抛出
RuntimeError
错误。如果指定的堆栈大小不合法,会抛出ValueError
错误并且不会修改堆栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要注意的是部分平台对于堆栈大小会有特定的限制,例如要求大于32KiB的堆栈大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关详细信息(4KiB页面比较普遍,在没有更具体信息的情况下,建议的方法是使用4096的倍数作为堆栈大小)。可用性: Windows,具有 POSIX 线程的系统。
这个模块同时定义了以下常量:
-
threading.
TIMEOUT_MAX
¶ 阻塞函数(
Lock.acquire()
,RLock.acquire()
,Condition.wait()
, ...)中形参 timeout 允许的最大值。传入超过这个值的 timeout 会抛出OverflowError
异常。3.2 新版功能.
这个模块定义了许多类,详见以下部分。
这个模块的设计大部分基于Java的线程模型。Java令锁和条件变量成为每个对象基本行为,但是在Python中它们是独立的对象。Python的 Thread
类支持Java的线程类的行为子集;目前没有优先级,没有线程组而且线程不能被销毁,停止,暂停,回复或者中断。当实现Java的线程静态方法时,映射到模块级别的函数。
下列描述的方法都是自动执行的。
线程本地数据¶
线程本地数据是特定线程的数据。管理线程本地数据,只需要创建一个 local
(或者一个子类型)的实例并在实例中储存属性:
mydata = threading.local()
mydata.x = 1
在不同的线程中,实例的值会不同。
-
class
threading.
local
¶ 一个代表线程本地数据的类。
更多相关细节和大量示例,参见
_threading_local
模块的文档。
线程对象¶
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.
当线程对象一但被创建,其活动一定会因调用线程的 start()
方法开始。这会在独立的控制线程调用 run()
方法。
一旦线程活动开始,该线程会被认为是 '存活的' 。当它的 run()
方法终结了(不管是正常的还是抛出未被处理的异常),就不是'存活的'。 is_alive()
方法用于检查线程是否存活。
其他线程可以调用一个线程的 join()
方法。这会阻塞调用该方法的线程,直到被调用 join()
方法的线程终结。
线程有名字。名字可以传递给构造函数,也可以通过 name
属性读取或者修改。
一个线程可以被标记成一个 "守护线程" 。这个标志的意义是,只有守护线程都终结,整个Python程序才会退出。初始值继承于创建线程。这个标志可以通过 daemon
特征属性或者 守护 构造函数参数来设置。
注解
守护线程在程序关闭时会突然关闭。他们的资源(例如已经打开的文档,数据库事务等等)可能没有被正确释放。如果你想你的线程正常停止,设置他们成为非守护模式并且使用合适的信号机制,例如: Event
。
有个 "主线程" 对象;这对应Python程序里面初始的控制线程。它不是一个守护线程。
"虚拟线程对象" 是可以被创建的。这些是对应于“外部线程”的线程对象,它们是在线程模块外部启动的控制线程,例如直接来自C代码。虚拟线程对象功能受限;他们总是被认为是存活的和守护模式,不能被 join()
。因为无法检测外来线程的终结,它们永远不会被删除。
-
class
threading.
Thread
(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)¶ 调用这个构造函数时,必需带有关键字参数。参数如下:
group 应该为
None
;为了日后扩展ThreadGroup
类实现而保留。target 是用于
run()
方法调用的可调用对象。默认是None
,表示不需要调用任何方法。name 是线程名称。默认情况下,由 "Thread-N" 格式构成一个唯一的名称,其中 N 是小的十进制数。
args 是用于调用目标函数的参数元组。默认是
()
。kwargs 是用于调用目标函数的关键字参数字典。默认是
{}
。如果不是
None
,不管当前线程是否守护模式,显式设置成 守护模式 。如果是None
(默认),守护模式特征属性继承自当前线程。如果子类型重载了构造函数,它一定要确保在做任何事前,先发起调用基类构造器(
Thread.__init__()
)。在 3.3 版更改: 加入 daemon 参数。
-
start
()¶ 开始线程活动。
它在一个线程里最多只能被调用一次。它安排对象的
run()
方法在一个独立的控制进程中调用。如果同一个线程对象中调用这个方法的次数大于一次,会抛出
RuntimeError
。
-
run
()¶ 代表线程活动的方法。
你可以在子类型里重载这个方法。标准的
run()
方法调用一个传递给对象构造函数的可调用对象,如果有,分别从 args 和 kwargs 参数中获取顺序和关键字参数。
-
join
(timeout=None)¶ 等待,直到线程终结。这会阻塞调用这个方法的线程,直到被调用
join()
的线程终结 -- 不管是正常终结还是抛出未处理异常 -- 或者直到发生超时,超时选项是可选的。当 timeout 参数存在而且不是
None
时,它应该是一个用于指定操作超时的以秒为单位的浮点数(或者分数)。因为join()
总是返回None
,所以你一定要在join()
后调用is_alive()
才能判断是否发生超时 -- 如果线程仍然存货,则join()
超时。当 timeout 参数不存在或者是
None
,这个操作会阻塞直到线程终结。一个线程可以被
join()
很多次。如果尝试加入当前线程会导致死锁,
join()
会引起RuntimeError
异常。如果尝试join()
一个尚未开始的线程,也会抛出相同的异常。
-
name
¶ 只用于识别的字符串。它没有语义。多个线程可以赋予相同的名称。 初始名称由构造函数设置。
-
ident
¶ 这个线程的 '线程标识符',如果线程尚未开始则为
None
。这是个非零整数。参见get_ident()
函数。当一个线程退出而另外一个线程被创建,线程标识符会被复用。即使线程退出后,仍可得到标识符。
-
is_alive
()¶ 返回线程是否存活。
当
run()
方法刚开始直到run()
方法刚结束,这个方法返回True
。模块函数enumerate()
返回包含所有存活线程的列表。
-
daemon
¶ 一个表示这个线程是(True)否(False)守护线程的布尔值。一定要在调用
start()
前设置好,不然会抛出RuntimeError
。初始值继承于创建线程;主线程不是守护线程,因此主线程创建的所有线程默认都是daemon
=False
。当没有存活的非守护线程时,整个Python程序才会退出。
-
CPython implementation detail: CPython下,因为 Global Interpreter Lock,一个时刻只有一个线程可以执行Python代码(尽管如此,某些性能导向的库可能会克服这个限制)。如果你想让你的应用更好的利用多核计算机的计算性能,推荐你使用 multiprocessing
或者 concurrent.futures.ProcessPoolExecutor
。但是如果你想同时运行多个I/O绑定任务,线程仍然是一个合适的模型。
锁对象¶
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.
锁同样支持 context management protocol。
当多个线程在 acquire()
等待状态转变为未锁定被阻塞,然后 release()
重置状态为未锁定时,只有一个线程能继续执行;至于哪个等待线程继续执行没有定义,并且会根据实现而不同。
所有方法都是自动执行的。
-
class
threading.
Lock
¶ 实现原始锁对象的类。一旦一个线程获得一个锁,会阻塞随后尝试获得锁的线程,直到它被释放;任何线程都可以释放它。
需要注意的是
Lock
其实是一个工厂函数,返回平台支持的具体锁类中最有效的版本的实例。-
acquire
(blocking=True, timeout=-1)¶ 可以阻塞或非阻塞地获得锁。
当调用时参数 blocking 设置为
True
(缺省值),阻塞直到锁被释放,然后将锁锁定并返回True
。When invoked with the blocking argument set to
False
, do not block. If a call with blocking set toTrue
would block, returnFalse
immediately; otherwise, set the lock to locked and returnTrue
.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. A timeout argument of
-1
specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false.The return value is
True
if the lock is acquired successfully,False
if not (for example if the timeout expired).在 3.2 版更改: 新的 timeout 形参。
在 3.2 版更改: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it.
-
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.
在未锁定的锁调用时,会引发
RuntimeError
异常。没有返回值。
-
递归锁对象¶
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. To unlock the lock, a thread calls
its release()
method. 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.
Reentrant locks also support the context management protocol.
-
class
threading.
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.-
acquire
(blocking=True, timeout=-1)¶ 可以阻塞或非阻塞地获得锁。
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. 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.
When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return 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. Return true if the lock has been acquired, false if the timeout has elapsed.
在 3.2 版更改: 新的 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. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread.
只有当前线程拥有锁才能调用这个方法。如果锁被释放后调用这个方法,会引起
RuntimeError
异常。没有返回值。
-
条件对象¶
条件变量总是与某种类型的锁对象相关联,锁对象可以通过传入获得,或者在缺省的情况下自动创建。当多个条件变量需要共享同一个锁时,传入一个锁很有用。锁是条件对象的一部分,你不必单独地跟踪它。
条件变量服从 上下文管理协议:使用 with
语句会在它包围的代码块内获取关联的锁。 acquire()
和 release()
方法也能调用关联锁的相关方法。
其它方法必须在持有关联的锁的情况下调用。 wait()
方法释放锁,然后阻塞直到其它线程调用 notify()
方法或 notify_all()
方法唤醒它。一旦被唤醒, wait()
方法重新获取锁并返回。它也可以指定超时时间。
The notify()
method wakes up one of the threads waiting for
the condition variable, if any are waiting. The notify_all()
method wakes up all threads waiting for the condition variable.
注意: notify()
方法和 notify_all()
方法并不会释放锁,这意味着被唤醒的线程不会立即从它们的 wait()
方法调用中返回,而是会在调用了 notify()
方法或 notify_all()
方法的线程最终放弃了锁的所有权后返回。
使用条件变量的典型编程风格是将锁用于同步某些共享状态的权限,那些对状态的某些特定改变感兴趣的线程,它们重复调用 wait()
方法,直到看到所期望的改变发生;而对于修改状态的线程,它们将当前状态改变为可能是等待者所期待的新状态后,调用 notify()
方法或者 notify_all()
方法。例如,下面的代码是一个通用的无限缓冲区容量的生产者-消费者情形:
# 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()
使用 while
循环检查所要求的条件成立与否是有必要的,因为 wait()
方法可能要经过不确定长度的时间后才会返回,而此时导致 notify()
方法调用的那个条件可能已经不再成立。这是多线程编程所固有的问题。 wait_for()
方法可自动化条件检查,并简化超时计算。
# Consume an item
with cv:
cv.wait_for(an_item_is_available)
get_an_available_item()
选择 notify()
还是 notify_all()
,取决于一次状态改变是只能被一个还是能被多个等待线程所用。例如在一个典型的生产者-消费者情形中,添加一个项目到缓冲区只需唤醒一个消费者线程。
-
class
threading.
Condition
(lock=None)¶ 实现条件变量对象的类。一个条件变量对象允许一个或多个线程在被其它线程所通知之前进行等待。
如果给出了非
None
的 lock 参数,则它必须为Lock
或者RLock
对象,并且它将被用作底层锁。否则,将会创建新的RLock
对象,并将其用作底层锁。在 3.3 版更改: 从工厂函数变为类。
-
acquire
(*args)¶ 请求底层锁。此方法调用底层锁的相应方法,返回值是底层锁相应方法的返回值。
-
release
()¶ 释放底层锁。此方法调用底层锁的相应方法。没有返回值。
-
wait
(timeout=None)¶ 等待直到被通知或发生超时。如果线程在调用此方法时没有获得锁,将会引发
RuntimeError
异常。这个方法释放底层锁,然后阻塞,直到在另外一个线程中调用同一个条件变量的
notify()
或notify_all()
唤醒它,或者直到可选的超时发生。一旦被唤醒或者超时,它重新获得锁并返回。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).When the underlying lock is an
RLock
, it is not released using itsrelease()
method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of theRLock
class is used, which really unlocks it even when it has been recursively acquired several times. 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 isFalse
.在 3.2 版更改: Previously, the method always returned
None
.
-
wait_for
(predicate, timeout=None)¶ Wait until a condition evaluates to true. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait.
This utility method may call
wait()
repeatedly until the predicate is satisfied, or until a timeout occurs. The return value is the last return value of the predicate and will evaluate toFalse
if the method timed out.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. The predicate is evaluated with the lock held.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.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.
The current implementation wakes up exactly n threads, if at least n threads are waiting. However, it's not safe to rely on this behavior. A future, optimized implementation may occasionally wake up more than n threads.
Note: an awakened thread does not actually return from its
wait()
call until it can reacquire the lock. Sincenotify()
does not release the lock, its caller should.
-
notify_all
()¶ Wake up all threads waiting on this condition. This method acts like
notify()
, but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, aRuntimeError
is raised.
-
信号量对象¶
这是计算机科学史上最古老的同步原语之一,早期的荷兰科学家 Edsger W. Dijkstra 发明了它。(他使用名称 P()
和 V()
而不是 acquire()
和 release()
)。
一个信号量管理一个内部计数器,该计数器因 acquire()
方法的调用而递减,因 release()
方法的调用而递增。 计数器的值永远不会小于零;当 acquire()
方法发现计数器为零时,将会阻塞,直到其它线程调用 release()
方法。
信号量对象也支持 context management protocol 。
-
class
threading.
Semaphore
(value=1)¶ 该类实现信号量对象。信号量对象管理一个原子性的计数器,代表
release()
方法的调用次数减去acquire()
的调用次数再加上一个初始值。如果需要,acquire()
方法将会阻塞直到可以返回而不会使得计数器变成负数。在没有显式给出 value 的值时,默认为1。可选参数 value 赋予内部计数器初始值,默认值为
1
。如果 value 被赋予小于0的值,将会引发ValueError
异常。在 3.3 版更改: 从工厂函数变为类。
-
acquire
(blocking=True, timeout=None)¶ 获取一个信号量。
在不带参数的情况下调用时:
- 如果在进入时,内部计数器的值大于0,将其减1并立即返回true。
- 如果在进入时,内部计数器的值为0,将会阻塞直到被
release()
方法的调用唤醒。一旦被唤醒(并且计数器值大于0),将计数器值减少1并返回true。线程会被每次release()
方法的调用唤醒。线程被唤醒的次序是不确定的。
在参数 blocking 被设置为false的情况下调用,将不会发生阻塞。如果不带参数的调用会发生阻塞的话,带参数的调用在相同情况下将会立即返回false。否则,执行和不带参数的调用一样的操作并返回true。
当参数 timeout 不为
None
时,将最多阻塞 timeout 秒。如果未能在时间间隔内成功获取信号量,将返回false,否则返回true。在 3.2 版更改: 新的 timeout 形参。
-
release
()¶ 释放一个信号量,将内部计数器的值增加1。当计数器原先的值为0且有其它线程正在等待它再次大于0时,唤醒正在等待的线程。
-
-
class
threading.
BoundedSemaphore
(value=1)¶ 该类实现有界信号量。有界信号量通过检查以确保它当前的值不会超过初始值。如果超过了初始值,将会引发
ValueError
异常。在大多情况下,信号量用于保护数量有限的资源。如果信号量被释放的次数过多,则表明出现了错误。没有指定时, value 的值默认为1。在 3.3 版更改: 从工厂函数变为类。
Semaphore
例子¶
信号量通常用于保护数量有限的资源,例如数据库服务器。在资源数量固定的任何情况下,都应该使用有界信号量。在生成任何工作线程前,应该在主线程中初始化信号量。
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
工作线程生成后,当需要连接服务器时,这些线程将调用信号量的 acquire 和 release 方法:
with pool_sema:
conn = connectdb()
try:
# ... use connection ...
finally:
conn.close()
使用有界信号量能减少这种编程错误:信号量的释放次数多于其请求次数。
事件对象¶
这是线程之间通信的最简单机制之一:一个线程发出事件信号,而其他线程等待该信号。
一个事件对象管理一个内部标志,调用 set()
方法可将其设置为true,调用 clear()
方法可将其设置为false,调用 wait()
方法将进入阻塞直到标志为true。
-
class
threading.
Event
¶ 实现事件对象的类。事件对象管理一个内部标志,调用
set()
方法可将其设置为true。调用clear()
方法可将其设置为false。调用wait()
方法将进入阻塞直到标志为true。这个标志初始时为false。在 3.3 版更改: 从工厂函数变为类。
-
is_set
()¶ 当且仅当内部标志为true时返回true。
-
wait
(timeout=None)¶ 阻塞线程直到内部变量为true。如果调用时内部标志为true,将立即返回。否则将阻塞线程,直到调用
set()
方法将标志设置为true或者发生可选的超时。当提供了timeout参数且不是
None
时,它应该是一个浮点数,代表操作的超时时间,以秒为单位(可以为小数)。当内部标志在调用wait进入阻塞后被设置为true,或者调用wait时已经被设置为true时,方法返回true。 也就是说,除非设定了超时且发生了超时的情况下将会返回false,其他情况该方法都将返回
True
。在 3.1 版更改: Previously, the method always returned
None
.
-
定时器对象¶
此类表示一个操作应该在等待一定的时间之后运行 --- 相当于一个定时器。 Timer
类是 Thread
类的子类,因此可以像一个自定义线程一样工作。
与线程一样,通过调用 start()
方法启动定时器。而 cancel()
方法可以停止计时器(在计时结束前), 定时器在执行其操作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。
例如:
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
栅栏对象¶
3.2 新版功能.
栅栏类提供一个简单的同步原语,用于应对固定数量的线程需要彼此相互等待的情况。线程调用 wait()
方法后将阻塞,直到所有线程都调用了 wait()
方法。此时所有线程将被同时释放。
栅栏对象可以被多次使用,但进程的数量不能改变。
这是一个使用简便的方法实现客户端进程与服务端进程同步的例子:
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)
-
class
threading.
Barrier
(parties, action=None, timeout=None)¶ 创建一个需要 parties 个线程的栅栏对象。如果提供了可调用的 action 参数,它会在所有线程被释放时在其中一个线程中自动调用。 timeout 是默认的超时时间,如果没有在
wait()
方法中指定超时时间的话。-
wait
(timeout=None)¶ 冲出栅栏。当栅栏中所有线程都已经调用了这个函数,它们将同时被释放。如果提供了 timeout 参数,这里的 timeout 参数优先于创建栅栏对象时提供的 timeout 参数。
函数返回值是一个整数,取值范围在0到 parties -- 1,在每个线程中的返回值不相同。可用于从所有线程中选择唯一的一个线程执行一些特别的工作。例如:
i = barrier.wait() if i == 0: # Only one thread needs to print this print("passed the barrier")
如果创建栅栏对象时在构造函数中提供了 action 参数,它将在其中一个线程释放前被调用。如果此调用引发了异常,栅栏对象将进入损坏态。
如果发生了超时,栅栏对象将进入破损态。
如果栅栏对象进入破损态,或重置栅栏时仍有线程等待释放,将会引发
BrokenBarrierError
异常。
-
reset
()¶ 重置栅栏为默认的初始态。如果栅栏中仍有线程等待释放,这些线程将会收到
BrokenBarrierError
异常。注意使用此函数时,如果有某些线程状态未知,则可能需其它的同步来确保线程已被释放。如果栅栏进入了破损态,最好废弃它并新建一个栅栏。
-
abort
()¶ 使栅栏进入破损态。这将导致所有已经调用和未来调用的
wait()
方法中引发BrokenBarrierError
异常。使用这个方法的一种情况是需要中止程序以避免死锁。更好的方式是:创建栅栏时提供一个合理的超时时间,来自动避免某个线程出错。
-
parties
¶ 冲出栅栏所需要的线程数量。
-
n_waiting
¶ 当前时刻正在栅栏中阻塞的线程数量。
-
broken
¶ 一个布尔值,值为
True
表明栅栏为破损态。
-
-
exception
threading.
BrokenBarrierError
¶ 异常类,是
RuntimeError
异常的子类,在Barrier
对象重置时仍有线程阻塞时和对象进入破损态时被引发。
在 with
语句中使用锁、条件和信号量¶
这个模块提供的带有 acquire()
和 release()
方法的对象,可以被用作 with
语句的上下文管理器。当进入语句块时 acquire()
方法会被调用,退出语句块时 release()
会被调用。因此,以下片段:
with some_lock:
# do something...
相当于:
some_lock.acquire()
try:
# do something...
finally:
some_lock.release()
现在 Lock
、 RLock
、 Condition
、 Semaphore
和 BoundedSemaphore
对象可以用作 with
语句的上下文管理器。