简体   繁体   English

时间:2019-05-16 标签:c++std::lock_guardscopereach

[英]c++ std::lock_guard scope reach

let's assume I have a function that acquires a lock and executes a fuction passed by argument:让我们假设我有一个获取锁并执行通过参数传递的函数的函数:

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

Also, I have a class that needs to acquire said lock for some of it's methods.另外,我有一个类需要为其某些方法获取所述锁。

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;

};

My doubt is if whenever I call GetValue() , looking at my acquireLock() method, is the execution() call also affected by the lock scope ?我的疑问是,是否每当我调用GetValue() ,查看我的acquireLock()方法, execution()调用是否也受锁定范围的影响?

auto myClass = new MyThreadSafeClass();
myClass->GetValue();

Looking at this , more specifically:看看这个,更具体地说:

When a lock_guard object is created, it attempts to take ownership of the mutex it is given.当一个 lock_guard 对象被创建时,它试图取得它所给的互斥锁的所有权。 When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.当控制离开创建 lock_guard 对象的作用域时,lock_guard 被销毁并释放互斥锁。

It's still unclear to me if what happens inside execution() code is still affected by the lock scope.我仍然不清楚execution()代码内部发生的事情是否仍受锁定范围的影响。

According to [stmt.return]/p3 :根据[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.调用结果的复制初始化在由 return 语句的操作数建立的完整表达式末尾的临时变量销毁之前进行排序,而后者又在局部变量([stmt .jump]) 包含 return 语句的块。

So we get:所以我们得到:

  1. The mutex is locked互斥锁被锁定
  2. execution() is called while holding the lock持有锁时调用execution()
  3. The lock is released锁被释放
  4. The evaluated value is returned to the caller (or the catch clause is entered)计算出的值返回给调用者(或输入catch子句)

In other words yes, it will work as intended.换句话说,是的,它将按预期工作。


Unrelated note: std::function isn't very efficient.无关注释: std::function效率不高。 Templating on the callable type should work better:可调用类型的模板应该工作得更好:

template<typename F>
auto doLocked(std::mutex& _lock, F const& f) -> decltype(f()) {
    std::lock_guard<std::mutex> lock(_lock);
    return f();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM