Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of Task615Solution-mbedos54 by
main.cpp
00001 #include "mbed.h" 00002 00003 #define RED_DONE 1 00004 #define YELLOW_DONE 2 00005 00006 00007 //Function declarations 00008 void countUP(); 00009 void countDOWN(); 00010 00011 //Digital outputs 00012 DigitalOut onBoardLED(LED1); 00013 DigitalOut redLED(D7); 00014 DigitalOut yellowLED(D6); 00015 DigitalOut greenLED(D5); 00016 00017 //Digital inputs 00018 DigitalIn onBoardSwitch(USER_BUTTON); 00019 DigitalIn SW1(D4); 00020 DigitalIn SW2(D3); 00021 00022 //MUTEX Lock 00023 Mutex *countLock; 00024 00025 //Thread ID for the Main function (CMSIS API) 00026 osThreadId tidMain; 00027 00028 //Stared mutable state 00029 volatile long long count = 0; 00030 00031 //Threads 00032 void countUP() 00033 { 00034 redLED = 1; 00035 00036 for (unsigned int n=0; n<10000; n++) { 00037 //Take lock 00038 countLock->lock(); 00039 00040 //Critical section(s) 00041 count++; 00042 count++; 00043 count++; 00044 count++; 00045 count++; 00046 count++; 00047 count++; 00048 count++; 00049 count++; 00050 count++; 00051 00052 //Release lock 00053 countLock->unlock(); 00054 } 00055 00056 redLED = 0; 00057 osSignalSet(tidMain, RED_DONE); //Signal main thread we are done 00058 } 00059 00060 void countDOWN() 00061 { 00062 yellowLED = 1; 00063 00064 for (unsigned int n=0; n<10000; n++) { 00065 //Take lock 00066 countLock->lock(); 00067 00068 //Critical section(s) 00069 count--; 00070 count--; 00071 count--; 00072 count--; 00073 count--; 00074 count--; 00075 count--; 00076 count--; 00077 count--; 00078 count--; 00079 00080 //Release lock 00081 countLock->unlock(); 00082 } 00083 00084 osSignalSet(tidMain, YELLOW_DONE); //Signal main thread we are done 00085 yellowLED = 0; 00086 } 00087 00088 00089 //Main thread 00090 int main() { 00091 Thread t1; 00092 Thread t2; 00093 00094 redLED = 0; 00095 yellowLED = 0; 00096 greenLED = 1; 00097 00098 //Main thread ID 00099 tidMain = Thread::gettid(); 00100 00101 //Create lock 00102 countLock = new Mutex(); 00103 00104 //Press the switch to run concurrently 00105 if (onBoardSwitch == 1) { 00106 printf("Running sequntially\n"); 00107 countUP(); 00108 countDOWN(); 00109 } else { 00110 printf("Running concurrently\n"); 00111 t1.start(countUP); 00112 t2.start(countDOWN); 00113 00114 //Wait for the ALL_ON signal 00115 Thread::signal_wait(RED_DONE,osWaitForever); 00116 Thread::signal_wait(YELLOW_DONE,osWaitForever); 00117 } 00118 00119 printf("Final result = %lld\n", count); 00120 if (count == 0) { 00121 greenLED = 0; 00122 } 00123 00124 //Tidy 00125 delete countLock; 00126 00127 while(true); 00128 }
Generated on Sun Jul 24 2022 09:36:16 by
1.7.2