【问题标题】:Use std::lock to protect return statement? [duplicate]使用 std::lock 保护 return 语句? [复制]
【发布时间】:2021-10-03 23:06:35
【问题描述】:

据我了解,std::lock 将部分锁定在其范围内。但是如果访问变量是在return 语句中执行的呢?示例:

// Looks safe...
bool foo
{
    std::lock_guard<decltype(myMutex)> tLock(myMutex);
    if (bar == 123)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Is it safe?
bool foo
{
    std::lock_guard<decltype(myMutex)> tLock(myMutex);
    return bar == 123;
}

【问题讨论】:

  • 在返回后调用析构函数,所以在这两种情况下都可以。

标签: c++ multithreading thread-safety


【解决方案1】:

return之后调用析构函数,

所以你在这两种情况下都很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2013-12-22
    相关资源
    最近更新 更多