我刚接触C++11线程。
下面的代码应该只由第一个线程执行。
其他线程(可能与第一个线程竞争)不应进入锁定的代码区域(这就是为什么使用 std::try_lock()
的原因)。
std::mutex mu;
// now ensure this will get called only once per event
if (std::try_lock(mu) != -1)
{
return;
}
{
std::lock_guard<std::mutex> guard(mu);
// critical section
} // mutex will be unlocked here
除了编写自己的lock_guard之外,是否有一种类似且标准的std::lock_guard
变体可用,但它将获取我未加锁的mutex(即以上std::try_lock()
的效果),并在该guard的析构函数被调用时简单地解锁它?