c++ - C++ std::lock_guard作用域范围

标签 c++ mutex locks

假设我有一个获取锁并执行参数传递的功能的函数:

template <typename T>
T acquireLock(std::mutex& _lock, const std::function<T()>& execution) {

  try {
    std::lock_guard<std::mutex> mutex (_lock);

    return execution();

  } catch (std::logic_error& error) {

    std::cerr << "[exception caught]\n\t" << error.what() << std::endl;

  }

  return false;
}
另外,我有一个需要为其某些方法获取所述锁的类。
class MyThreadSafeClass {

 public:

  bool Init();
  bool StopApi();
  unsigned int GetValue() {

      auto ret = acquireLock<unsigned int>(_lock, [this]() -> unsigned int {

        // does some work that's not thread-safe...
        return value;

      });

      return ret;
  }

 private:

  bool _ready = false;
  std::mutex _lock;

};
我的疑问是,每当我调用GetValue()并查看acquireLock()方法时,execution()调用是否也会受到锁定范围的影响?
auto myClass = new MyThreadSafeClass();
myClass->GetValue();
查看this,更具体地说:

When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.


我仍然不清楚execution()代码内部发生的事情是否仍受锁定范围的影响。

最佳答案

根据[stmt.return]/p3:

  1. The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block enclosing the return statement.

这样我们得到:
  • 互斥锁已锁定
  • 按住锁时调用
  • execution()
  • 锁已释放
  • 评估值返回给调用者(或输入catch子句)

  • 换句话说,它将按预期工作。

    不相关的说明:std::function效率不高。在可调用类型上模板应更好地工作:
    template<typename F>
    auto doLocked(std::mutex& _lock, F const& f) -> decltype(f()) {
        std::lock_guard<std::mutex> lock(_lock);
        return f();
    }
    

    关于c++ - C++ std::lock_guard作用域范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64070131/

    相关文章:

    java - 两个线程、两个同步块(synchronized block)和一个内在锁

    python - 如何在C++中使用 "in"关键字

    javascript - node.js(javascript)中的系统范围互斥锁

    c++ - 为什么pthread_cond_signal会导致死锁

    multithreading - 唤醒/等待比赛锁定?

    c# - 在 C# 中使用锁访问方法

    c++ - 如何正确删除从另一个 DLL 接收的派生对象?

    c++ - 为什么 Crypto++ SecByteBlock 下标有效

    c++ - 指向抽象基类的指针需要一些转换吗? C++

    c - 在c中的进程间同步中互斥体的使用