Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_mutex_lock() get the lock? That is, are calls to pthread_mutex_lock() in FIFO order? If not, what, if any, order are they in? Thanks!

like image 681
shanet Avatar asked Feb 18 '13 23:02

shanet


2 Answers

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

like image 81
autistic Avatar answered Sep 24 '22 06:09

autistic


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

like image 25
LihO Avatar answered Sep 24 '22 06:09

LihO