In this example semaphores are used to ensure the running order of the program threads. Analogous to the relay race.

Dependencies:   mbed mbed-rtos

Files at this revision

API Documentation at this revision

Comitter:
cspista
Date:
Thu Mar 17 12:38:12 2022 +0000
Commit message:
Final 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	Thu Mar 17 12:38:12 2022 +0000
@@ -0,0 +1,27 @@
+#include "mbed.h"
+#include "rtos.h"
+
+Semaphore sem[] = {(1),(0),(0),(0)};          // Set of semaphores
+DigitalOut led[] = {(D13),(D12),(D11),(D10)}; // Set of LEDs
+
+void led_thread(void const* args) {
+    int i = (int)args-1;                      // Idx of this task
+    int inext = (i+1)%4;                      // Idx of next task
+    while (true) {
+        sem[i].wait();
+        led[i] = 0;                           // ith LED on
+        Thread::wait(500+rand()%500);
+        led[i] = 1;                           // ith LED off
+        sem[inext].release();                 // Start new task
+    }
+}
+
+int main (void) {
+    for(int i=0; i<4; i++) {
+        led[i]=1;                             // LEDs off
+    }
+    Thread t2(led_thread, (void *)2U);
+    Thread t3(led_thread, (void *)3U);
+    Thread t4(led_thread, (void *)4U);       
+    led_thread((void *)1U);
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Thu Mar 17 12:38:12 2022 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed-rtos/#5713cbbdb706
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Thu Mar 17 12:38:12 2022 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed/builds/65be27845400
\ No newline at end of file