In this example semaphores are used to ensure the running order of the program threads. Analogous to the relay race.
main.cpp@0:6d3407923be9, 2022-03-17 (annotated)
- Committer:
- cspista
- Date:
- Thu Mar 17 12:38:12 2022 +0000
- Revision:
- 0:6d3407923be9
Final version
Who changed what in which revision?
| User | Revision | Line number | New contents of line |
|---|---|---|---|
| cspista | 0:6d3407923be9 | 1 | #include "mbed.h" |
| cspista | 0:6d3407923be9 | 2 | #include "rtos.h" |
| cspista | 0:6d3407923be9 | 3 | |
| cspista | 0:6d3407923be9 | 4 | Semaphore sem[] = {(1),(0),(0),(0)}; // Set of semaphores |
| cspista | 0:6d3407923be9 | 5 | DigitalOut led[] = {(D13),(D12),(D11),(D10)}; // Set of LEDs |
| cspista | 0:6d3407923be9 | 6 | |
| cspista | 0:6d3407923be9 | 7 | void led_thread(void const* args) { |
| cspista | 0:6d3407923be9 | 8 | int i = (int)args-1; // Idx of this task |
| cspista | 0:6d3407923be9 | 9 | int inext = (i+1)%4; // Idx of next task |
| cspista | 0:6d3407923be9 | 10 | while (true) { |
| cspista | 0:6d3407923be9 | 11 | sem[i].wait(); |
| cspista | 0:6d3407923be9 | 12 | led[i] = 0; // ith LED on |
| cspista | 0:6d3407923be9 | 13 | Thread::wait(500+rand()%500); |
| cspista | 0:6d3407923be9 | 14 | led[i] = 1; // ith LED off |
| cspista | 0:6d3407923be9 | 15 | sem[inext].release(); // Start new task |
| cspista | 0:6d3407923be9 | 16 | } |
| cspista | 0:6d3407923be9 | 17 | } |
| cspista | 0:6d3407923be9 | 18 | |
| cspista | 0:6d3407923be9 | 19 | int main (void) { |
| cspista | 0:6d3407923be9 | 20 | for(int i=0; i<4; i++) { |
| cspista | 0:6d3407923be9 | 21 | led[i]=1; // LEDs off |
| cspista | 0:6d3407923be9 | 22 | } |
| cspista | 0:6d3407923be9 | 23 | Thread t2(led_thread, (void *)2U); |
| cspista | 0:6d3407923be9 | 24 | Thread t3(led_thread, (void *)3U); |
| cspista | 0:6d3407923be9 | 25 | Thread t4(led_thread, (void *)4U); |
| cspista | 0:6d3407923be9 | 26 | led_thread((void *)1U); |
| cspista | 0:6d3407923be9 | 27 | } |