What is the `pthread_mutex_lock()` wake order with multiple threads waiting?

后端 未结 3 1516
北海茫月
北海茫月 2020-12-19 01:35

Suppose I have multiple threads blocking on a call to pthread_mutex_lock(). When the mutex becomes available, does the first thread that called pthread_mu

3条回答
  •  -上瘾入骨i
    2020-12-19 02:14

    FIFO ordering is about the least efficient mutex wake order possible. Only a truly awful implementation would use it. The thread that ran the most recently may be able to run again without a context switch and the more recently a thread ran, more of its data and code will be hot in the cache. Reasonable implementations try to give the mutex to the thread that held it the most recently most of the time.

    Consider two threads that do this:

    1. Acquire a mutex.
    2. Adjust some data.
    3. Release the mutex.
    4. Go to step 1.

    Now imagine two threads running this code on a single core CPU. It should be clear that FIFO mutex behavior would result in one "adjust some data" per context switch -- the worst possible outcome.

    Of course, reasonable implementations generally do give some nod to fairness. We don't want one thread to make no forward progress. But that hardly justifies a FIFO implementation!

提交回复
热议问题