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 //Shared mutable state
00020 volatile long long counter = 0; //Volatile means it must be stored in memory
00021 
00022 //Increment the shared variable 
00023 void countUp()
00024 {
00025     //RED MEANS THE COUNT UP FUNCTION IS IN ITS CRITICAL SECTION
00026     red_led = 1;
00027     for (unsigned int n=0; n<N; n++) {
00028         counter++; 
00029         counter++;
00030         counter++;
00031         counter++;
00032         counter++;
00033         counter++;
00034         counter++;
00035         counter++;
00036         counter++;
00037         counter++;           
00038     }  
00039     red_led = 0; 
00040     
00041 }
00042 
00043 //Decrement the shared variable
00044 void countDown()
00045 {
00046     //YELLOW MEANS THE COUNT DOWN FUNCTION IS IN ITS CRITICAL SECTION
00047     yellow_led = 1;
00048     for (unsigned int n=0; n<N; n++) {
00049         counter--;
00050         counter--;
00051         counter--;
00052         counter--;
00053         counter--;
00054         counter--;
00055         counter--;
00056         counter--;
00057         counter--;
00058         counter--;           
00059     }
00060     yellow_led = 0;
00061           
00062 }
00063 int main() {
00064     
00065     green_led = 1;
00066     
00067     //Start competing threads
00068     t1.start(countUp);
00069     t2.start(countDown);
00070     
00071     //These threads DO exit, so let's wait for BOTH to finish
00072     t1.join();  //Wait for thread t1 to finish
00073     t2.join();  //Wait for thread t2 to finish
00074     
00075     //Did the counter end up at zero?
00076     if (counter == 0) {
00077         green_led = 0;   
00078     }
00079         
00080     //Now spin-lock for ever
00081     while(1) { 
00082         asm("nop");
00083     };
00084 }
00085