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 —— 互斥锁对象

class mutex.Mutex

创建一个未锁定的互斥锁对象。

release() None

解锁互斥锁。如果互斥锁当前未被锁定,则引发 mutex.MutexException

test() bool

尝试以非阻塞方式获取互斥锁。成功时返回 True,如果互斥锁已被锁定则返回 False

要以阻塞方式获取互斥锁,请将该实例用作上下文管理器(with 语句)。退出时互斥锁会自动释放。

异常

exception mutex.MutexException

OSError 的子类。当互斥锁已处于解锁状态时由 Mutex.release 引发。