Demonstration of a message queue + memory pool

main.cpp

Committer:
noutram
Date:
2016-03-08
Revision:
0:f916cefba2f4
Child:
1:4fb27aea76b2

File content as of revision 0:f916cefba2f4:

#include "mbed.h"
#include "rtos.h"

#define RED_DONE 1
#define YELLOW_DONE 2


//Function declarations
void countUP(void const *args);
void countDOWN(void const *args);

//Digital outputs
DigitalOut onBoardLED(LED1);
DigitalOut redLED(D7);
DigitalOut yellowLED(D6);
DigitalOut greenLED(D5);

//Digital inputs
DigitalIn  onBoardSwitch(USER_BUTTON);
DigitalIn  SW1(D4);
DigitalIn  SW2(D3);

//Thread object references
Thread* t1;
Thread* t2;

//Thread ID for the Main function (CMSIS API)
osThreadId tidMain;

//Stared mutable state
volatile long long count = 0;

//Threads
void countUP(void const *args)
{
    redLED = 1;
    
    for (unsigned int n=0; n<10000; n++) {
        count++;
        count++;        
        count++;
        count++;    
        count++;
        count++; 
        count++;
        count++;
        count++;
        count++;   
    }
    
    redLED = 0;
    osSignalSet(tidMain, RED_DONE);  //Signal main thread we are done
}

void countDOWN(void const *args)
{
    yellowLED = 1;
    
    for (unsigned int n=0; n<10000; n++) {
        count--;
        count--;        
        count--;
        count--;    
        count--;
        count--; 
        count--;
        count--;
        count--;
        count--;               
    }   
    
    osSignalSet(tidMain, YELLOW_DONE); //Signal main thread we are done
    yellowLED = 0;
}


//Main thread
int main() {
    redLED    = 0;
    yellowLED = 0;
    greenLED  = 1;
    
    //Main thread ID
    tidMain = Thread::gettid();  
    
    //Press the switch to run concurrently
    if (onBoardSwitch == 1) {
        printf("Running sequntially\n");
        countUP(NULL);
        countDOWN(NULL);        
    } else {
        printf("Running concurrently\n");
        Thread t1(countUP);           
        Thread t2(countDOWN);    
  
        //Wait for the ALL_ON signal
        Thread::signal_wait(RED_DONE,osWaitForever);
        Thread::signal_wait(YELLOW_DONE,osWaitForever);        
    }

    printf("Final result = %lld\n", count);
    if (count == 0) {
        greenLED = 0;
    }
    while(true);
}