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

Committer:
icserny
Date:
Wed Feb 10 13:03:43 2016 +0000
Revision:
0:6d2b4755a904
First version

Who changed what in which revision?

UserRevisionLine numberNew contents of line
icserny 0:6d2b4755a904 1 /** 10_rtos_mutex
icserny 0:6d2b4755a904 2 * Example of mutex usage to protect shared access to stdio (printf).
icserny 0:6d2b4755a904 3 * Note that this kind of protection is needed in case of Cortex-M0 MCU-s
icserny 0:6d2b4755a904 4 * which use C microlib. Larger MCUs (like Cortex M3), however, use
icserny 0:6d2b4755a904 5 * the C stdlib which already provides a mutex to protect access to stdio.
icserny 0:6d2b4755a904 6 */
icserny 0:6d2b4755a904 7
icserny 0:6d2b4755a904 8 #include "mbed.h"
icserny 0:6d2b4755a904 9 #include "rtos.h"
icserny 0:6d2b4755a904 10
icserny 0:6d2b4755a904 11 Mutex stdio_mutex;
icserny 0:6d2b4755a904 12
icserny 0:6d2b4755a904 13 void notify(const char* name, int state) {
icserny 0:6d2b4755a904 14 stdio_mutex.lock();
icserny 0:6d2b4755a904 15 printf("%s: %d\n\r", name, state);
icserny 0:6d2b4755a904 16 stdio_mutex.unlock();
icserny 0:6d2b4755a904 17 }
icserny 0:6d2b4755a904 18
icserny 0:6d2b4755a904 19 void test_thread(void const *args) {
icserny 0:6d2b4755a904 20 while (true) {
icserny 0:6d2b4755a904 21 notify((const char*)args, 0); Thread::wait(1000);
icserny 0:6d2b4755a904 22 notify((const char*)args, 1); Thread::wait(1000);
icserny 0:6d2b4755a904 23 }
icserny 0:6d2b4755a904 24 }
icserny 0:6d2b4755a904 25
icserny 0:6d2b4755a904 26 int main() {
icserny 0:6d2b4755a904 27 Thread t2(test_thread, (void *)"Th 2");
icserny 0:6d2b4755a904 28 Thread t3(test_thread, (void *)"Th 3");
icserny 0:6d2b4755a904 29 test_thread((void *)"Th 1");
icserny 0:6d2b4755a904 30 }