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