Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fair Reentrant Lock C++

I'm working on a program which suffer from starvation when one thread is doing more work than another. Critical section is protected by a reentrant QMutex, which is not fair.

In Java, you can specify a fairness parameter for a lock. Does C++,(or boost libraries) have any fair reentrant lock available? Preferably up to C++11.

I did some research before, there is shared_lock in boost, but I do not need a read/write lock. Just a lock which will guarantee that each thread has equal chances to enter the critical section.

Thank you very much.

like image 820
Veaceslav Avatar asked Oct 20 '22 02:10

Veaceslav


1 Answers

C++ thread primitives are really based on Posix threads, and Posix does not have any fair mutexes. However, your question indicates that there is a problem with your design. There are two issues here:

  1. Re-entrant mutexes are sign of the problem. You need to be 100% in control of mutex ownership and lifecycle. If you need re-entrant mutex, it means, design is sloppy.
  2. Thread starvation in your description is a result of improperly designed thread communication. If a thread needs a mutex held for the duration of the work, it means, you are effectively designing a single-threaded system, and need no threads whatsoever.
like image 81
SergeyA Avatar answered Oct 21 '22 17:10

SergeyA