MUTEX _TIME BASED LOCK UNLOCK SYSTEM to avoid priority inversion and deadlock or thread stuck issue.

main.cpp

Committer:
radhey04ec
Date:
2020-07-26
Revision:
1:4f150e2895bf
Parent:
0:f8e6d9529dbd

File content as of revision 1:4f150e2895bf:

// MUTEX : PART 2  -MUTEX TIME BASED LOCKING

/*As we know MUTEX have ownership in locking mechanism. Thread which locked code using mutex flag then only same thread can unblock it
If you have not enough knowledge regarding RTOS then it leads some dangerous situation like priority inversion and Deadlock

Time based unlocking help us to avoid DEADLOCK.
Here mutex automatically unlock  the block after ending time period

Program created by : Jaydeep shah -radhey04ec@gmail.com
Date :  26 July 2020
*/


/* Function use
bool trylock_for(Kernel::Clock::duration_u32 rel_time);
Tries to lock the mutex. If it succeeds within the specified time frame (interval) the mutex is locked and stays locked until unlocked by calling the unlock function.

bool trylock_until(Kernel::Clock::time_point abs_time); 
Tries to lock the mutex. If it succeeds before the given time point is reached it locks the mutex and the mutex stays locked until unlocked by calling the unlock function.

*/

#include "mbed.h"

Mutex Lock;
Thread T1,T2;
bool V;
void common_block(const char* name, int state)
{
    printf("\n Thread arrive %s %d \n", name, state);
    if (Lock.trylock_for(50)) { // try to lock the mutex: timeout = 50 ms-----------------------------
        printf("\n Inside  %s state %d \n", name, state);
        ThisThread::sleep_for(6000);               //some how process stuck in wait state
        printf("\n outside %s state %d \n", name, state);
        Lock.unlock(); // unlock
    }
    else
    {
        //Thread back to other work/next process if fail to acquire Critical section
        //Thread not stuck for getting mutex flag it can do other important work also
        printf("\n %s thread fail to lock state %d",name,state);
    }
}
void fun(void const *arg)
{
    while(true)
    {
        common_block((const char *)arg,0);  //PASS STATE 0
        wait(2);
        common_block((const char *)arg,1);// PASS STATE 1
        wait(2);
    }
}

int main()
{
 T1.start(callback(fun,(void *)"T1"));
 T2.start(callback(fun,(void *)"T2"));
 fun((void *)"main");
}