Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock std::mutex without starvation

In my program I have a single mutex and two threads. One of these threads acquires the lock very often. The other thread tries to acquire but has to wait forever.

Could it be that the lock is acquired so quick after releasing it that the other thread does not get a chance? Does a mutex always give everyone a chance? If not, what would be a good solution?(some kind of FIFO lock?)

I am using std::mutex and std::lock_guard.

Question expansion seccpur pointed out that an std::condition_variable would be a solution to this problem. How does this scale with three threads? Does std::condition_variable assure every thread gets a turn? Assuming you use notify_one().

like image 666
Aart Stuurman Avatar asked Oct 20 '25 21:10

Aart Stuurman


1 Answers

An std::mutex does not guarantee giving everyone an equal chance. So it is possible that one thread starves another. The first thing you can try is to insert std::this_thread::yield() and see if it helps. If this does not help, then your code must have logic errors. Post some portion of the code and we can help you diagnose further.

like image 164
Donghui Zhang Avatar answered Oct 23 '25 10:10

Donghui Zhang



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!