2
votes

Imagine a thread blocks on a condition variable:

pthread_mutex_lock (mutex);
do_something ();
pthread_cond_wait(cond, mutex); // [1]
do_something_else ();
pthread_mutex_unlock (mutex);

The mutex is unlocked and a different thread trying to lock the mutex is unblocked:

pthread_mutex_lock (mutex);
do_some_work ();
pthread_cond_signal (cond);
pthread_mutex_unlock (mutex);

At the same time there's another thread waiting to acquire the ownership of the critical section:

pthread_mutex_lock (mutex); // [2]
do_some_random_work ();
pthread_mutex_unlock (mutex);

Now, the question is: When pthread_cond_signal() is called, is it guaranteed that the pthread_cond_wait() [1] will unblock before pthread_mutex_lock() [2]?

The POSIX specification seems to say nothing about the case.

1

1 Answers

5
votes

No, it's not.

Descriptions of pthread_cond_signal() are sometimes worded as

When each thread unblocked as a result of a pthread_cond_signal() or pthread_cond_broadcast() returns from its call to pthread_cond_wait() or pthread_cond_timedwait(), the thread owns the mutex with which it called pthread_cond_wait() or pthread_cond_timedwait(). The thread(s) that are unblocked contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

(Taken from this link)

As you can see, it's worded as "as if each had called pthread_mutex_lock()". Thus, there is no priorization of this implied pthread_mutex_lock call compared to an actual pthread_mutex_lock call from another thread.