Search code examples
c++multithreadingmutexatomiccondition-variable

How to atomically check if mutex is locked?


Consider this:

// Somewhere
std::mutex mutex;
std::unique_lock lock{mutex};
std::condition_variable condition;

// Thread01
condition.wait(lock);

// Thread02
while (lock.owns_lock());

So I got a situation like this where the loop at Thread02 never ends, regardless of the fact that Thread01 is waiting for the condition.

This means that unlocking the lock at std::condition_variable::wait does not synchronize with checking if the lock is locked at std::unique_lock::owns_lock. Here it is explicitly told that the wait "Atomically unlocks lock..." but here nothing is told about owns_lock of being atomic or being synchronised with the lock operations.

So the question is: how can I atomically check it the wait has atomically unlocked the lock?

EDIT:

The desire is to know at Thread02 if Thread01 is waiting for the condition. That's why I've accepted the answer.


Solution

  • You can momentarily lock the lock and get the desired Thread02:

    // Thread02
    std::unique_lock{mutex};
    // mutex isn’t locked