In this example three semaphores are used to mantain the monotonic execution order of three threads. Each task is consumer of a semaphore and at the same time producer of an another semaphore.Watching the RGB LED you can see the order of execution.

Dependencies:   mbed-rtos mbed

Revision:
0:61ad4bb19246
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Feb 10 12:40:31 2016 +0000
@@ -0,0 +1,57 @@
+/** 10_rtos_3semaphores
+ * In this example three semaphores are used to mantain the
+ * monotonic execution order of three threads.
+ * Each task is consumer of a semaphore and at the same time
+ * producer of an another semaphore.
+ * Watching the RGB LED you can see the order of execution.
+ *
+ * Hardware requirements:
+ *  - FRDM-KL25Z board
+ */
+
+#include "mbed.h"
+#include "rtos.h"
+
+Semaphore s1(1);                            //allow task1 to run
+Semaphore s2(0);                            //s2 has no token at start
+Semaphore s3(0);                            //s3 has no token at start
+DigitalOut led1(LED1);                      //Red LED
+DigitalOut led2(LED2);                      //Green LED
+DigitalOut led3(LED3);                      //Blue LED
+
+void thread1(void const* args) {
+    while (true) {
+        s1.wait();
+        led1 = 0;                           //Red LED ON
+        Thread::wait(500+rand()%500);
+        led1 = 1;                           //Red LED OFF
+        s2.release();
+    }
+}
+
+void thread2(void const* args) {
+    while (true) {
+        s2.wait();
+        led2 = 0;                           //Green LED ON
+        Thread::wait(500+rand()%500);
+        led2 = 1;                           //Green LED OFF
+        s3.release();
+    }
+}
+
+void thread3(void const* args) {
+    while (true) {
+        s3.wait();
+        led3 = 0;                           //Blue LED ON
+        Thread::wait(500+rand()%500);
+        led3 = 1;                           //Blue LED OFF
+        s1.release();
+    }
+}
+
+int main (void) {
+    led1 = 1; led2 = 1; led3 = 1;           //Switch off all LEDs
+    Thread t2(thread2);                     //Define and run thread2
+    Thread t3(thread3);                     //Define and run thread3
+    thread1(NULL);                          //Run thread1
+}