Synchronizing threads using condition variables (monitors)

461 Views Asked by At

I need to synchronize multiple threads (using POSIX threads). Moreover, I am making use of condition variables (monitors) to achieve that.

The issue is that I must implement a "first come first served" strategy. Say multiple threads are waiting for another thread to signal that condition change, does the pthread_cond_wait call put the threads in a queue itself or should I define an explicit queue to achieve this? A possible solution to this might also be making use of locks.

1

There are 1 best solutions below

0
On

The Pthreads API does not guarantee fairness for the pthread_cond_wait + pthread_cond_signal/pthread_cond_broadcast combo. The spec explicitly states that the scheduling policy will determine the order in which the waiting threads will wake up:

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked.

If you don't want to rely on the scheduler (even if it's one that has "aged well" like Linux' CFS), you need to control the parking and unparking yourself.

As for the implementation of a fair waiting queue, you can build on top of an MCS queue.