mutex --- mutex 模块¶
mutex 模块提供了一个互斥原语,用于保护关键代码段或共享数据,使其免受中断服务程序与主线程的并发访问。
锁的获取和释放通过上下文管理器(with 语句)执行,它会阻塞直到互斥锁可用。还提供了一个非阻塞的 Mutex.test() 方法。
示例:
from mutex import Mutex
mtx = Mutex()
# Acquire for a critical section (blocks if already held).
with mtx:
# ... protected code, e.g. shared buffer access ...
pass
# Or try without blocking.
if mtx.test():
try:
# ... protected code ...
pass
finally:
mtx.release()
class Mutex —— 互斥锁对象¶
异常¶
- exception mutex.MutexException¶
OSError的子类。当互斥锁已处于解锁状态时由Mutex.release引发。