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

后端 未结 3 1504
北海茫月
北海茫月 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条回答
  • 2020-12-19 02:01

    "If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex."

    Aside from that, the answer to your question isn't specified by the POSIX standard. It may be random, or it may be in FIFO or LIFO or any other order, according to the choices made by the implementation.

    0 讨论(0)
  • 2020-12-19 02:05

    When the mutex becomes available, does the first thread that called pthread_mutex_lock() get the lock?

    No. One of the waiting threads gets a lock, but which one gets it is not determined.

    FIFO order?

    FIFO mutex is rather a pattern already. See Implementing a FIFO mutex in pthreads

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题