Nelson P Nelson P - 20 days ago 6
C++ Question

C++ : Is possible to use std::condition_variable with std::lock_guard?

I am using a

std::condition_variable
combined with a
std::unique_lock
like this.

std::mutex a_mutex;
std::condition_variable a_condition_variable;
std::unique_lock<std::mutex> a_lock(a_mutex);
a_condition_variable.wait(a_lock, [this] {return something;});
//Do something
a_lock.unlock();


It works fine. As I understand,
std::condition_variable
accepts a
std::unique_lock
for it to wait. But, I am trying to combine it with
std::lock_guard
but not able to.

My question is: Is it possible to replace
std::unique_lock
with a
std::lock_guard
instead ?
This can relieve me from manually unlocking the lock every time I use it.

Answer

No, a std::unique_lock is needed if it is used with std::condition_variable. std::lock_guard may have less overhead, but it cannot be used with std::condition_variable.

But the std::unique_lock doesn't need to be manually unlocked, it also unlocks when it goes out of scope, like std::lock_guard. So the waiting code could be written as:

std::mutex a_mutex;
std::condition_variable a_condition_variable;
{
    std::unique_lock<std::mutex> a_lock(a_mutex);
    a_condition_variable.wait(a_lock, [this] {return something;});
    //Do something
}

See http://en.cppreference.com/w/cpp/thread/unique_lock

Comments