gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:09:57 33 4
gpt4 key购买 nike

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

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 ofthe mutex it is given. When control leaves the scope in which thelock_guard object was created, the lock_guard is destructed and themutex 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/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com