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 RecursiveMutex object. You will often include a RecursiveMutex either as a member of your class, or you can make RecursiveMutex a public superclass of your class, which will make the lock, try_lock, and unlock methods automatically available to your class.

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.