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

Files at this revision

API Documentation at this revision

Comitter:
icserny
Date:
Wed Feb 10 13:03:43 2016 +0000
Commit message:
First version

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-rtos.lib Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /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");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Wed Feb 10 13:03:43 2016 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed-rtos/#3d9d2b8b8f17
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Wed Feb 10 13:03:43 2016 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/6f327212ef96
\ No newline at end of file