c++lockingmutexstarvation

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().


Solution

  • 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.