假设我有一个获取锁并执行参数传递的功能的函数:
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()
代码内部发生的事情是否仍受锁定范围的影响。
最佳答案
- 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/