Abhinav Gauniyal Abhinav Gauniyal - 3 months ago 19
C++ Question

scope of std::lock_guard inside if block

Currently studying about

std::mutex
and would love some help. If I've a code that looks like -

....
if(returnBoolValue())
{
std::lock_guard<std::mutex> lock(mutex_var);
....
....
}
....


is the
std::lock_guard
guarding the function returning the value inside if condition? ie.
returnBoolValue()


And how should I improve it so that function call is inside the guard as well, if possible?





Answer

Currently it's not possible to do this without adding another scope (C++17 has a way to do this)

A solution would be

....
{
   std::lock_guard<std::mutex> lock(mutex_var);
   if(returnBoolValue())
   {
      ....
      ....
   }
}
....

C++ 17 way:

....
if(std::lock_guard<std::mutex> lock(mutex_var); returnBoolValue())
{
   ....
   ....
}
....