Jaydeep Shah
/
21_MUTEX_LOCK_UNLOCK
MUTEX and its use in MBED MUTEX LOCK and Unlock mechanism
main.cpp
- Committer:
- radhey04ec
- Date:
- 2020-07-26
- Revision:
- 2:0cf7e435eeb8
- Parent:
- 1:605f5624661e
File content as of revision 2:0cf7e435eeb8:
/* 21_ MUTEX a Guard at door - Basic program MUTEX allow only one Thread / Function call inside CS, Mutex have ownership type locking mechanism. Procees /or Thread who locked block,only same process /or thread can unlock it. */ //PROGRAM CREATED BY : JAYDEEP SHAH -- radheec@gmail.com //DATE : 25 JULY 20 ,VERSION 1.0 //OUTPUT : USE SERIAL TERMINAL 9600 8-N-1 #include "mbed.h" //MBED LIBRARY Mutex M_LOCK; // Create MUTEX OBJECT -class = MUTEX //Create Two Thread Thread t2; Thread t3; //Here below section act as CS critical section void common_function(const char *name, int state) //TWO ARGUMENTS 1) WHO CALLED THIS FUNCTION 2)STATE OF CALLER { printf("Thread arrive at door %s: %d\n\r", name, state); M_LOCK.lock(); //After arrive lock the code---------------------------LOCK THE BLOCK printf("This Thread lock the code %s: %d\n\r", name, state); wait(0.5); //sleep printf("Thread cross & unlock %s: %d\n\r", name, state); //OUTSIDE CODE BLOCK --------- M_LOCK.unlock(); //After completing task unlock the code ------------- UNLOCK THE BLOCK //DO NOT WRITE any print statement after unlock() it create missunderstanding .... /* print statement require more clk cycle,after unlock the MUTEX Flag - schedular quickly schedule next thread before print the statement.*/ } //Function -- We will connect more than one thread with this function //So because of context switching this Function become sharable between multiple process. void test_thread(void const *args) { while (true) { common_function((const char *)args, 0); ThisThread::sleep_for(500); common_function((const char *)args, 1); ThisThread::sleep_for(500); } } int main() { t2.start(callback(test_thread, (void *)"Th 2")); t3.start(callback(test_thread, (void *)"Th 3")); test_thread((void *)"Th 1"); // DIRECT CALL via main thread }