5

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?


Abhinav Gauniyal
  • 7,034
  • 7
  • 50
  • 93
  • 1
    the mutex will only guard everything after `returnBoolValue`and only the part inside the `if` scope. What do you mean with `prove`? Improve? in what way improve then? – Hayt Sep 05 '16 at 12:37
  • @Hayt I need the `returnBoolValue()` to be covered by guard as well. – Abhinav Gauniyal Sep 05 '16 at 12:44

3 Answers3

10

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())
{
   ....
   ....
}
....
Hayt
  • 5,210
  • 30
  • 37
6

The lock guard locks the mutex when it's constructed: that is, when control flow of your program reaches the declaration of lock. It releases (unlocks) the mutex when the guard is destructed, which happens when control flows through the } terminating the then-block (either by flowing through there naturally, or "forced" by a return, throw, or jump statement).

This of course also shows how you can extend the scope "protected" by the mutex: extend the scope of the lock variable:

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

Note that I added an extra block around the "lock + if" pair, to make sure the mutex is unlocked as soon as the if-block finishes.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

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

No. The critical section begins at the point of declaration of the guard. The guard is declared after the condition - so it is not guarded.

And how should I improve it

If you need the condition to be guarded as well, then move the guard before the if statement.

eerorika
  • 232,697
  • 12
  • 197
  • 326