std::lock_guard 的范围在 if 块内

scope of std::lock_guard inside if block

目前正在研究 std::mutex,希望得到一些帮助。如果我的代码看起来像 -

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

std::lock_guard守卫函数返回if条件内的值吗? IE。 returnBoolValue()

如果可能的话,我应该如何改进它,以便函数调用也在守卫内部?


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

没有。临界区从守卫的声明点开始。守卫是在条件之后声明的——所以它不受守卫。

And how should I improve it

如果您还需要保护条件,则将保护移到 if 语句之前。

目前如果不添加另一个作用域是不可能做到这一点的(C++17 有办法做到这一点)

一个解决方案是

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

C++ 17 方式:

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

锁守卫在构建时锁定互斥锁:也就是说,当程序的控制流到达 lock 的声明时。它在守卫被破坏时释放(解锁)互斥量,这发生在控制流过 } 终止 then-block 时(通过自然流过那里,或者 "forced" 通过 return, throw, 或跳转语句).

这当然也展示了如何通过互斥量扩展范围 "protected":扩展 lock 变量的范围:

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

请注意,我在“lock + if”对周围添加了一个额外的块,以确保在 if 块完成后立即解锁互斥体。