![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Random Delay With Thread
main.cpp@0:be029d41beb4, 2017-01-20 (annotated)
- Committer:
- thinkfire
- Date:
- Fri Jan 20 11:52:20 2017 +0000
- Revision:
- 0:be029d41beb4
tested
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
thinkfire | 0:be029d41beb4 | 1 | #include "mbed.h" |
thinkfire | 0:be029d41beb4 | 2 | #include "rtos.h" |
thinkfire | 0:be029d41beb4 | 3 | |
thinkfire | 0:be029d41beb4 | 4 | DigitalOut led1(LED1); |
thinkfire | 0:be029d41beb4 | 5 | DigitalOut led2(LED2); |
thinkfire | 0:be029d41beb4 | 6 | DigitalOut led3(LED3); |
thinkfire | 0:be029d41beb4 | 7 | DigitalOut led4(LED4); |
thinkfire | 0:be029d41beb4 | 8 | |
thinkfire | 0:be029d41beb4 | 9 | void led1_thread(void const *args) { |
thinkfire | 0:be029d41beb4 | 10 | while (true) { |
thinkfire | 0:be029d41beb4 | 11 | led1 = !led1; |
thinkfire | 0:be029d41beb4 | 12 | Thread::wait((rand()%700)+1); |
thinkfire | 0:be029d41beb4 | 13 | } |
thinkfire | 0:be029d41beb4 | 14 | } |
thinkfire | 0:be029d41beb4 | 15 | |
thinkfire | 0:be029d41beb4 | 16 | void led2_thread(void const *args) { |
thinkfire | 0:be029d41beb4 | 17 | while (true) { |
thinkfire | 0:be029d41beb4 | 18 | led2 = !led2; |
thinkfire | 0:be029d41beb4 | 19 | Thread::wait((rand()%700)+1); |
thinkfire | 0:be029d41beb4 | 20 | } |
thinkfire | 0:be029d41beb4 | 21 | } |
thinkfire | 0:be029d41beb4 | 22 | |
thinkfire | 0:be029d41beb4 | 23 | void led3_thread(void const *args) { |
thinkfire | 0:be029d41beb4 | 24 | while (true) { |
thinkfire | 0:be029d41beb4 | 25 | led3 = !led3; |
thinkfire | 0:be029d41beb4 | 26 | Thread::wait((rand()%700)+1); |
thinkfire | 0:be029d41beb4 | 27 | } |
thinkfire | 0:be029d41beb4 | 28 | } |
thinkfire | 0:be029d41beb4 | 29 | |
thinkfire | 0:be029d41beb4 | 30 | void led4_thread(void const *args) { |
thinkfire | 0:be029d41beb4 | 31 | while (true) { |
thinkfire | 0:be029d41beb4 | 32 | led4 = !led4; |
thinkfire | 0:be029d41beb4 | 33 | Thread::wait((rand()%700)+1); |
thinkfire | 0:be029d41beb4 | 34 | } |
thinkfire | 0:be029d41beb4 | 35 | } |
thinkfire | 0:be029d41beb4 | 36 | |
thinkfire | 0:be029d41beb4 | 37 | int main() { |
thinkfire | 0:be029d41beb4 | 38 | //Create a thread to execute the function led2_thread |
thinkfire | 0:be029d41beb4 | 39 | Thread thread1(led1_thread); |
thinkfire | 0:be029d41beb4 | 40 | Thread thread2(led2_thread); |
thinkfire | 0:be029d41beb4 | 41 | Thread thread3(led3_thread); |
thinkfire | 0:be029d41beb4 | 42 | Thread thread4(led4_thread); |
thinkfire | 0:be029d41beb4 | 43 | |
thinkfire | 0:be029d41beb4 | 44 | //led2_thread is executing concurrently with main at this point |
thinkfire | 0:be029d41beb4 | 45 | |
thinkfire | 0:be029d41beb4 | 46 | while (true) { |
thinkfire | 0:be029d41beb4 | 47 | } |
thinkfire | 0:be029d41beb4 | 48 | } |