Threading

RecursiveMutex class - Threading

A Mutex can only be locked once, even from the same thread. RecursiveMutex, on the other hand, allows the same thread to lock the mutex multiple times and maintains a counter so the underlying resource is freed only after the last balanced unlock(). This is useful if you lock a shared resource in a low-level of your code, but also may need to lock your resource in a higher level of your code in some cases, so the low-level lock could be called when already locked.

RecursiveMutex constructor - Threading

// PROTOTYPE
RecursiveMutex()

Construct a new recursive mutex object. You will typically include a RecursiveMutex either as a member of your class.

In theory, it would be handy to make RecursiveMutex a superclass of your class. Having the lock() and unlock() methods would make it work with WITH_LOCK(). However, you must not do this if your class will ever be instantiated as a global variable. The reason is that the Mutex constructor calls os_mutex_create, and this is not safe during global object construction. If you use a singleton that's only instantiated during setup or later, that would be safe.

RecursiveMutex functions cannot be called from an ISR.

RecursiveMutex::lock - Threading

// PROTOTYPE
void lock();

Lock the recursive mutex. If the mutex is already locked from a different thread, blocks the current thread until is is unlocked.

If the recursive mutex is already locked from this thread, the lock will proceed without blocking, and the resource will only be released when the last balanced unlock() is called.

You cannot lock a recursive mutex from an ISR.

RecursiveMutex::trylock - Threading

// PROTOTYPE
bool trylock();
bool try_lock();

Attempts to lock the recursive mutex If it is unlocked or locked from this thread, it will be locked and true is returned. If it is already locked, false is returned and the thread that previously held the lock will continue to hold the lock.

You cannot lock a recursive mutex from an ISR.

RecursiveMutexMutex::unlock - Threading

// PROTOTYPE
void unlock();

Unlocks the recursive mutex. Typically only the thread that locked the mutex will unlock it.

Within a single thread, multiple nested lock() and unlock() pairs are counted, so the underlying resource is only released to other threads after the last balanced unlock().

You cannot unlock a recursive mutex from an ISR.