Here's an experiment using the thread C++ class.
Initial conditions (ICs):
- Thread A has a condition variable that is waiting on a lock (on a mutex).
- Thread B has the mutex locked.
- 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.