Question

Here's an experiment using the thread C++ class.

Initial conditions (ICs):

  1. Thread A has a condition variable that is waiting on a lock (on a mutex).
  2. Thread B has the mutex locked.
  3. Thread C hasn't done anything.

Now thread C calls m.lock() (when creating a lock). Afterwards, thread B notifies the condition variable. Does the fact that thread A was waiting on a condition variable that was waiting on a lock on that mutex make it any more or less likely that it will lock the mutex first, or is thread C just as likely to do so?

Here's an example of what I mean:

#include <condition_variable>
#include <mutex>
#include <thread>

std::condition_variable cv;
std::mutex m;

void funcB()
{
    std::unique_lock<std::mutex> B_lk(m);
    sleep(2); // allow thread C to attempt lock; IC-2
    cv.notify_one();
    B_lk.unlock();
}

void funcC()
{
    sleep(1); // allow thread B to lock; IC-3
    std::unique_lock<std::mutex> C_lk(m);
    /* Perform task C */
}

int main (int argc, char* argv[]) // thread A
{
    std::unique_lock<std::mutex> A_lk(m);
    std::thread threadB(funcB);
    std::thread threadC(funcC);
    cv.wait(A_lk); // IC-1

    /* Perform task A */

    /* Clean up and return */
}

I think threads A and C are (theoretically, anyway) equally likely to lock the mutex after thread B unlocks it because I didn't see any mention of priority in the C++ Standard. I read through many other questions about locking priority here on SO, but I couldn't find any that addressed this particular question.

Was it helpful?

Solution

It's deliberately unspecified by the standard to allow freedom of implementation. Specifically, C++11 §30.5.1 Class condition variable [thread.condition.condvar] states:

void notify_one() noexcept;

7 Effects: If any threads are blocked waiting for *this, unblocks one of those threads.

void notify_all() noexcept;

8 Effects: Unblocks all threads that are blocked waiting for *this.

There is no claim made about preference/fairness/priority to any thread(s), simply "unblocks one" or "unblocks all."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top