Example of mutex usage to protect shared access to stdio (printf). Note that this kind of protection is needed in case of Cortex-M0 MCU-s which use C microlib. Larger MCUs (like Cortex M3), however, use the C stdlib which already provides a mutex to protect access to stdio.

Dependencies:   mbed-rtos mbed

main.cpp

Committer:
icserny
Date:
2016-02-10
Revision:
0:6d2b4755a904

File content as of revision 0:6d2b4755a904:

/** 10_rtos_mutex
 * Example of mutex usage to protect shared access to stdio (printf).
 * Note that this kind of protection is needed in case of Cortex-M0 MCU-s
 * which use C microlib. Larger MCUs (like Cortex M3), however, use
 * the C stdlib which already provides a mutex to protect access to stdio.
 */

#include "mbed.h"
#include "rtos.h"
 
Mutex stdio_mutex; 
 
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); Thread::wait(1000);
        notify((const char*)args, 1); Thread::wait(1000);
    }
}
 
int main() {
    Thread t2(test_thread, (void *)"Th 2");
    Thread t3(test_thread, (void *)"Th 3");         
    test_thread((void *)"Th 1");
}