Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Granting priority access to a std::mutex

I currently have two functions like this that share the same mutex.

void fooA()
{
   {
     std::lock_guard<std::mutex> guard(myMutex);
     doWork()
   }
}

void fooB()
{
   {
     std::lock_guard<std::mutex> guard(myMutex);
     doWork()
   }
}

My question is if it is possible to specify that fooA() mutex should be given priority/preference ? I understand that mutexes is first come first serve. Say there are four threads t1,t2,t3,t4. Now suppose thread t1 currently owns the mutex in fooB() and t2 and t3 are waiting in line for the mutex in fooB() whereas thread t4 is waiting in line for the mutex at fooA(). What I would like is for thread t4 to be given priority next since its accessing fooA() and lets t2,t3 continue waiting. All of this should be done after t1 releases the mutex

like image 935
Rajeshwar Avatar asked Jun 11 '26 07:06

Rajeshwar


1 Answers

Considering that your problem is not in the MUTEX lock of functions running inside your process but of priority queuing within your multi-threaded environment, as long as you have access to the thread creation functions-- to set the priority of each called thread, you can use:

#include <sched.h>

int sched_setscheduler(pid_t pid, int policy,
                       const struct sched_param *param);

int sched_getscheduler(pid_t pid);

struct sched_param {
    ...
    int sched_priority;
    ...
};

Some issues you may run into are (1) if the newly minted priority thread is then commandeering the mutex without giving the lower priority threads a chance. (2) If you set multiple threads to equally high priority (can be overridden by correcting this or setting a Round Robin Scheduling Scheme) (3) Priority Inversion is still possible. This is my first SO answer so hope it helps! If you want more info check out the references, especially (2) which gives primitive answers to this problem!

References: (1) https://linux.die.net/man/2/sched_setscheduler (2) How to give priority to privileged thread in mutex locking? (3) https://www.ibm.com/docs/en/aix/7.2?topic=programming-synchronization-scheduling

like image 103
Vikyat Miryala Avatar answered Jun 13 '26 23:06

Vikyat Miryala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!