Solution to Task 6.1.7 Note the order in which the locks are taken. Updated for mbed os 5.4
Fork of Task617Solution-mbedos54 by
main.cpp
00001 #include "mbed.h" 00002 #include "rtos.h" 00003 #include "string.h" 00004 #include <stdio.h> 00005 #include <ctype.h> 00006 00007 #define DELAY 200 00008 00009 //Digital outputs 00010 DigitalOut onBoardLED(LED1); 00011 DigitalOut redLED(D7); 00012 DigitalOut yellowLED(D6); 00013 DigitalOut greenLED(D5); 00014 00015 //Serial Interface 00016 Serial pc(USBTX, USBRX); 00017 00018 //Digital inputs 00019 DigitalIn onBoardSwitch(USER_BUTTON); 00020 DigitalIn SW1(D4); 00021 DigitalIn SW2(D3); 00022 00023 //Thread ID for the Main function (CMSIS API) 00024 osThreadId tidMain; 00025 00026 //Thread sychronisation primatives 00027 Mutex lock1; 00028 Mutex lock2; 00029 unsigned long sw1Count = 0; 00030 unsigned long sw2Count = 0; 00031 00032 void thread1() 00033 { 00034 pc.printf("Entering thread 1\n"); 00035 while (true) { 00036 yellowLED = 1; 00037 00038 //Start critical section 00039 lock1.lock(); 00040 00041 sw1Count++; 00042 printf("\nCount1 = %lu", sw1Count); 00043 00044 Thread::wait(1); //1ms 00045 00046 //End critical section 00047 lock1.unlock(); 00048 00049 if (SW1 == 1) { 00050 lock2.lock(); 00051 sw2Count--; 00052 lock2.unlock(); 00053 } 00054 00055 yellowLED = 0; 00056 Thread::wait(DELAY); 00057 } 00058 } 00059 00060 void thread2() 00061 { 00062 pc.printf("Entering thread 2\n"); 00063 while (true) { 00064 redLED = 1; 00065 00066 //Start critical section 00067 lock2.lock(); 00068 00069 sw2Count++; 00070 printf("\nCount2 = %lu", sw2Count); 00071 00072 Thread::wait(1); //1ms 00073 00074 //End critical section 00075 lock2.unlock(); 00076 00077 if (SW2 == 1) { 00078 lock1.lock(); 00079 sw1Count--; 00080 lock1.unlock(); 00081 } 00082 00083 redLED = 0; 00084 Thread::wait(DELAY); 00085 00086 } 00087 } 00088 00089 00090 //Main thread 00091 int main() { 00092 redLED = 0; 00093 yellowLED = 0; 00094 greenLED = 0; 00095 00096 //Main thread ID 00097 tidMain = Thread::gettid(); 00098 00099 //Threads 00100 Thread t1, t2; 00101 00102 t1.start(thread1); 00103 t2.start(thread2); 00104 00105 pc.printf("Main Thread\n"); 00106 while (true) { 00107 Thread::wait(osWaitForever); 00108 } 00109 00110 } 00111 00112
Generated on Sun Jul 24 2022 15:47:25 by 1.7.2