Mistake on this page?
Report an issue in GitHub or email us

Mutex

A Mutex is used to synchronize the execution of threads, for example to protect the access to a shared resource.

Warning - ISR: 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, nothing happens; attempts to lock a mutex succeed immediately, regardless of whether the lock is actually free. In other words, if you acquire a mutex lock in an ISR, you can break the thread safety mechanisms and introduce race-conditions into an otherwise safe piece of code. Future versions of Mbed OS will provide warnings and ultimately prevent this from happening.

Mutex class reference

Public Member Functions
 Mutex ()
 Mutex (const char *name)
osStatus lock (uint32_t millisec=osWaitForever)
bool trylock ()
osStatus unlock ()

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.

Warning: stdio, malloc and new in ISR

stdioprintfputcgetcmallocnew
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.