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

Dependencies:   mbed mbed-rtos

main.cpp

Committer:
cspista
Date:
2022-03-17
Revision:
0:6d3407923be9

File content as of revision 0:6d3407923be9:

#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);
}