![](/media/cache/group/default_image.jpg.50x50_q85.jpg)
Demonstration of a spin lock
Dependencies: ELEC350-Practicals-FZ429
Fork of Task617Solution-mbedos-FZ429 by
main.cpp
- Committer:
- noutram
- Date:
- 2017-10-31
- Revision:
- 7:bd75e7717b58
- Parent:
- 6:d16ce38e9b8a
- Child:
- 8:ad00c9036add
File content as of revision 7:bd75e7717b58:
#include "mbed.h" #include "rtos.h" #include "string.h" #include <stdio.h> #include <ctype.h> #define DELAY 200 DigitalOut onBoardLED(LED1); DigitalOut redLED(PE_15); DigitalOut yellowLED(PB_10); DigitalOut greenLED(PB_11); DigitalIn onBoardSwitch(USER_BUTTON); DigitalIn SW1(PE_12); DigitalIn SW2(PE_14); //Thread ID for the Main function (CMSIS API) osThreadId tidMain; //Thread sychronisation primatives Mutex lock1; Mutex lock2; unsigned long sw1Count = 0; unsigned long sw2Count = 0; void thread1() { printf("Entering thread 1\n"); while (true) { yellowLED = 1; //Start critical section lock1.lock(); sw1Count++; printf("\nCount1 = %lu", sw1Count); Thread::wait(1); //1ms //End critical section lock1.unlock(); if (SW1 == 1) { lock2.lock(); sw2Count--; lock2.unlock(); } yellowLED = 0; Thread::wait(DELAY); } } void thread2() { printf("Entering thread 2\n"); while (true) { redLED = 1; //Start critical section lock2.lock(); sw2Count++; printf("\nCount2 = %lu", sw2Count); Thread::wait(1); //1ms //End critical section lock2.unlock(); if (SW2 == 1) { lock1.lock(); sw1Count--; lock1.unlock(); } redLED = 0; Thread::wait(DELAY); } } //Main thread int main() { redLED = 0; yellowLED = 0; greenLED = 0; //Main thread ID tidMain = Thread::gettid(); //Threads Thread t1, t2; t1.start(thread1); t2.start(thread2); printf("Main Thread\n"); while (true) { Thread::wait(osWaitForever); } }