:mod:`mutex` --- mutex module ============================= .. module:: mutex :synopsis: mutex module The ``mutex`` module is used for creating mutexes. ``mutex``模块用于创建互斥锁。 class Mutex -- mutex object 类互斥对象 =========================== A mutex is an object enabling threads of execution to protect critical sections of code from reentrancy or to temporarily protect critical data sets from being updated by other threads. The term "mutex" derives from the notion of mutual exclusion. A mutex usually provides three methods: 互斥锁是一种允许执行线程保护代码的关键部分免受攻击的对象 可重入性或临时保护关键数据集不被其他线程更新。 术语"mutex"源于互斥的概念。互斥锁通常提供三种方法: | lock() (POSIX pthread_mutex_lock): wait until the mutex is free, then lock it | unlock() (POSIX pthread_mutex_unlock): Immediate return. unlock the mutex. | test() (POSIX pthread_mutex_trylock): Immediate return. test if it is locked. | lock() (POSIX pthread_mutex_lock):等待直到互斥锁空闲,然后锁定它 | unlock() (POSIX pthread_mutex_unlock):立即返回。对互斥锁进行解锁。 | test() (POSIX pthread_mutex_trylock):立即返回。测试它是否锁定。 In this implementation lock and unlock is controlled by a context manager. 在此实现中,锁定和解锁由上下文管理器控制。 In the context of MicroPython a mutex provides a mechanism where an interrupt service routine (ISR) can test whether the main loop was using critical variables at the time the interrupt occurred, and if so avoid modifying those variables. Typical usage:: 在MicroPython上下文中,互斥锁提供了中断服务例程(ISR)的机制。 可以测试主循环在中断发生时是否使用了关键变量,以及 如果是这样,就避免修改这些变量。典型的用法:: import pyb, mutex mutex = mutex.Mutex() data_ready = False def callback(): # Timer or interrupt callback def callback(): # 计时器或中断回调 global data_ready if mutex.test(): data_ready = True # Update critical variables # 更新关键变量 mutex.release() else: # defer any update # 延迟任何更新 # Associate callback with device (pin or timer) # 关联回调设备(pin或定时器) while True: # code # 代码 if data_ready: with mutex: data_ready = False # Access critical variables # 访问关键变量 # more code # 更多的代码 Note that the with statement will execute immediately because no other process runs a with block on the same mutex instance. 注意,with语句将立即执行,因为没有其他进程在on上运行with块 同一个互斥对象实例。 `Linux man page `_ References describing mutex and semaphore objects 描述互斥和信号量对象的引用 | `geeksforgeeks `_ | `stackoverflow `_ | `differencebetween `_ Constructors 构造函数 ------------ .. class:: Mutex() Creates an unlocked mutex object. 创建一个解锁的互斥对象。 Methods 方法 ------- .. method:: mjpeg.release() Unlock the mutex. 对互斥锁进行解锁。 .. method:: mjpeg.test() Try to acquire the mutex in a non-blocking way. Return ``True`` on success and ``False`` on failure. 尝试以非阻塞的方式获取互斥锁。成功返回``True``,失败返回``False``。 You may also acquire the mutex in a blocking way by using ``with``. 你也可以通过使用``with``以一种阻塞的方式获取互斥锁。