2019

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 void countUp();
00003 void countDown();
00004 
00005 #define N 1000000
00006 #define RELEASED 0
00007 #define PRESSED  1
00008 
00009 //Hardware
00010 DigitalOut red_led(PE_15);     //CountUp is in its critical section
00011 DigitalOut yellow_led(PB_10);  //CountDown is in its critical section
00012 DigitalOut green_led(PB_11);   //counter != 0
00013 DigitalIn button(USER_BUTTON);
00014 
00015 //Additional Threads
00016 Thread t1;
00017 Thread t2;
00018 
00019 //MUTEX Lock to avoid data corruption
00020 Mutex mutex;
00021 
00022 //Shared mutable state
00023 volatile long long counter = 0; //Volatile means it must be stored in memory
00024 
00025 //Increment the shared variable 
00026 void countUp()
00027 {
00028     //RED MEANS THE COUNT UP FUNCTION IS IN ITS CRITICAL SECTION
00029     red_led = 1;
00030     for (unsigned int n=0; n<N; n++) {
00031         mutex.lock();
00032         counter++; 
00033         counter++;
00034         counter++;
00035         counter++;
00036         counter++;
00037         counter++;
00038         counter++;
00039         counter++;
00040         counter++;
00041         counter++;
00042         mutex.unlock();           
00043     }  
00044     red_led = 0; 
00045     
00046 }
00047 
00048 //Decrement the shared variable
00049 void countDown()
00050 {
00051     //YELLOW MEANS THE COUNT DOWN FUNCTION IS IN ITS CRITICAL SECTION
00052     yellow_led = 1;
00053     for (unsigned int n=0; n<N; n++) {
00054         mutex.lock();
00055         counter--;
00056         counter--;
00057         counter--;
00058         counter--;
00059         counter--;
00060         counter--;
00061         counter--;
00062         counter--;
00063         counter--;
00064         counter--; 
00065         mutex.unlock();          
00066     }
00067     yellow_led = 0;
00068           
00069 }
00070 int main() {
00071     
00072     green_led = 1;
00073     
00074     //Start competing threads
00075     t1.start(countUp);
00076     t2.start(countDown);
00077     
00078     //These threads DO exit, so let's wait for BOTH to finish
00079     t1.join();  //Wait for thread t1 to finish
00080     t2.join();  //Wait for thread t2 to finish
00081     
00082     //Did the counter end up at zero?
00083     if (counter == 0) {
00084         green_led = 0;   
00085     }
00086         
00087     //Now spin-lock for ever
00088     while(1) { 
00089         asm("nop");
00090     };
00091 }
00092