简体   繁体   中英

Synchronizing threads using condition variables (monitors)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM