Mutex Example

Dependencies:   mbed-rtos mbed

Fork of rtos_mutex by mbed official

Committer:
thinkfire
Date:
Fri Jan 20 11:51:11 2017 +0000
Revision:
7:ff2e3fbefea7
Parent:
6:1ae0d86d2020
tested

Who changed what in which revision?

UserRevisionLine numberNew contents of line
emilmont 1:0f886ffbe0c1 1 #include "mbed.h"
thinkfire 7:ff2e3fbefea7 2 #include "rtos.h"
thinkfire 7:ff2e3fbefea7 3
thinkfire 7:ff2e3fbefea7 4 DigitalOut led1(LED1);
thinkfire 7:ff2e3fbefea7 5 DigitalOut led2(LED2);
thinkfire 7:ff2e3fbefea7 6
thinkfire 7:ff2e3fbefea7 7 Mutex led_mutex;
emilmont 1:0f886ffbe0c1 8
thinkfire 7:ff2e3fbefea7 9 void delay(void){
thinkfire 7:ff2e3fbefea7 10 for(int i=0;i<65000;i++){
thinkfire 7:ff2e3fbefea7 11 for(int j=0;j<100;j++)
thinkfire 7:ff2e3fbefea7 12 {
thinkfire 7:ff2e3fbefea7 13 }
thinkfire 7:ff2e3fbefea7 14 }
emilmont 1:0f886ffbe0c1 15 }
thinkfire 7:ff2e3fbefea7 16
thinkfire 7:ff2e3fbefea7 17 void test_thread1(void const *args) {
emilmont 1:0f886ffbe0c1 18 while (true) {
thinkfire 7:ff2e3fbefea7 19 led_mutex.lock();
thinkfire 7:ff2e3fbefea7 20 printf("thd1 toogling\n");
thinkfire 7:ff2e3fbefea7 21 led1 = !led1;
thinkfire 7:ff2e3fbefea7 22 delay();
thinkfire 7:ff2e3fbefea7 23 led_mutex.unlock();
thinkfire 7:ff2e3fbefea7 24 Thread::wait(1000);
emilmont 1:0f886ffbe0c1 25 }
emilmont 1:0f886ffbe0c1 26 }
emilmont 1:0f886ffbe0c1 27
thinkfire 7:ff2e3fbefea7 28 void test_thread2(void const *args) {
thinkfire 7:ff2e3fbefea7 29 while (true) {
thinkfire 7:ff2e3fbefea7 30 led_mutex.lock();
thinkfire 7:ff2e3fbefea7 31 printf("thd2 toogling\n");
thinkfire 7:ff2e3fbefea7 32 led1 = !led1;
thinkfire 7:ff2e3fbefea7 33 delay();
thinkfire 7:ff2e3fbefea7 34 led_mutex.unlock();
thinkfire 7:ff2e3fbefea7 35 Thread::wait(1000);
thinkfire 7:ff2e3fbefea7 36 }
thinkfire 7:ff2e3fbefea7 37 }
thinkfire 7:ff2e3fbefea7 38 void test_thread(void const *args) {
thinkfire 7:ff2e3fbefea7 39 while (true) {
thinkfire 7:ff2e3fbefea7 40 led_mutex.lock();
thinkfire 7:ff2e3fbefea7 41 printf("main toogling\n");
thinkfire 7:ff2e3fbefea7 42 led1 = !led1;
thinkfire 7:ff2e3fbefea7 43 delay();
thinkfire 7:ff2e3fbefea7 44 led_mutex.unlock();
thinkfire 7:ff2e3fbefea7 45 Thread::wait(1000);
thinkfire 7:ff2e3fbefea7 46 }
thinkfire 7:ff2e3fbefea7 47 }
thinkfire 7:ff2e3fbefea7 48
emilmont 1:0f886ffbe0c1 49 int main() {
thinkfire 7:ff2e3fbefea7 50 Thread t2(test_thread1, (void *)"Th 1");
thinkfire 7:ff2e3fbefea7 51 Thread t3(test_thread2, (void *)"Th 2");
thinkfire 7:ff2e3fbefea7 52
thinkfire 7:ff2e3fbefea7 53 test_thread((void *)"main");
thinkfire 7:ff2e3fbefea7 54 }