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.
Diff: main.cpp
- Revision:
- 0:6d2b4755a904
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Wed Feb 10 13:03:43 2016 +0000 @@ -0,0 +1,30 @@ +/** 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"); +}