Mutex
Mutex class hierarchy
A Mutex is used to synchronize the execution of threads, for example to protect the access to a shared resource.
The Mutex
methods cannot be called from interrupt service routines (ISR). In the current version of Mbed OS, if you attempt to use a mutex from within an ISR, it will treat that as a fatal system error, and you will see an error like this:
++ MbedOS Error Info ++
Error Status: 0x80020115 Code: 277 Module: 2
Error Message: Mutex lock failed
Location: 0x80026B3
Error Value: 0xFFFFFFFA
Current Thread: Id: 0x20004F54 Entry: 0x8002ABF StackSize: 0x1000 StackMem: 0x20004F98 SP: 0x2004FEF8
For more info, visit: https://armmbed.github.io/mbedos-error/?error=0x80020115
-- MbedOS Error Info --
If synchronization is required in ISR, consider using semaphores.
Note: Mbed OS uses the PlatformMutex class instead of the RTOS mutex for all drivers.
Mutex class reference
Public Member Functions | |
Mutex () | |
Create and Initialize a Mutex object. More... | |
Mutex (const char *name) | |
Create and Initialize a Mutex object. More... | |
void | lock () |
Wait until a Mutex becomes available. More... | |
osStatus | lock (uint32_t millisec) |
Wait until a Mutex becomes available. More... | |
bool | trylock () |
Try to lock the mutex, and return immediately. More... | |
bool | trylock_for (uint32_t millisec) |
Try to lock the mutex for a specified time. More... | |
bool | trylock_until (uint64_t millisec) |
Try to lock the mutex until specified time. More... | |
void | unlock () |
Unlock the mutex that has previously been locked by the same thread. More... | |
osThreadId_t | get_owner () |
Get the owner the this mutex. More... | |
~Mutex () | |
Mutex destructor. More... |
Mutex example
Use Mutex to protect printf().
#include "mbed.h"
Mutex stdio_mutex;
Thread t2;
Thread t3;
void notify(const char* name, int state) {
stdio_mutex.lock();
printf("%s: %d\n\r", name, state);
stdio_mutex.unlock();
}
void test_thread(void const *args) {
while (true) {
notify((const char*)args, 0); wait(1);
notify((const char*)args, 1); wait(1);
}
}
int main() {
t2.start(callback(test_thread, (void *)"Th 2"));
t3.start(callback(test_thread, (void *)"Th 3"));
test_thread((void *)"Th 1");
}
Note: C standard library Mutexes
The Arm C standard library already has Mutexes in place to protect the access to stdio
, so on the LPC1768 the above example is not necessary. On the other hand, the LPC11U24 does not provide default stdio
Mutexes, making the above example a necessity.
Note: Because of the mutexes in the Arm C standard library, you cannot use stdio
(printf
, putc
, getc
and so on), malloc
and new
in ISR.
Related content
- PlatformMutex API reference.