让我们假设我有一个函数,它获取一个锁并执行通过参数传递的函数:
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();
看看这,更具体地说:
当创建一个lock_guard对象时,它试图获得它所给出的互斥对象的所有权。当控件离开创建lock_guard对象的作用域时,将销毁lock_guard并释放互斥对象。
我仍然不清楚execution()
代码中发生的事情是否仍然受到锁作用域的影响。
发布于 2020-09-25 19:53:01
所以我们得到:
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();
}
https://stackoverflow.com/questions/64070131
复制相似问题