if块内std :: lock_guard的范围 [英] scope of std::lock_guard inside if block

查看:163
本文介绍了if块内std :: lock_guard的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
    ....
    ....
}
....

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 so that function call is inside the guard as well, if possible?

推荐答案

当前,如果不添加其他作用域,则无法执行此操作(C ++ 17可以执行此操作)

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

一个解决方案是

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

C ++ 17种方式:

C++ 17 way:

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

这篇关于if块内std :: lock_guard的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆