On a multi-threaded Linux application I use a mutex for critical sections. This works very well except for the fairness issue. It can happen that a thread leaving a critical section and re-entering right away does not give any other thread a chance. For example
while(true)
{
critsect.enter();
... do calculations ...
... maybe call a blocking operation so we sleep ...
critsect.leave();
}
might very likely stop any other thread to enter the same critical section. Mutexe are not fair.
Is there a solution to making a fair critical section? I was thinking of adding a queue so that critical sections are executed in the order of their 'arrival'. Alternatively at least a counter to maybe do a pthread_yield() after unlock if other threads are waiting.
Is there a recommended practice for this kind of requirement?
It can happen that a thread leaving a critical section and re-entering right away does not give any other thread a chance
is not true. – Enneahedron