我是C++ 11线程的新手.
以下代码只能由第一个线程执行.
其他线程(可能与第一个线程竞争)不应该进入锁定的代码区域(这就是为什么std::try_lock()存在).
std::mutex mutex;
// now ensure this will get called only once per event
if (std::try_lock(_mutex) != -1)
{
return;
}
{
std::lock_guard<std::mutex> guard(_mutex);
// critical section
} // mutex will be unlocked here
Run Code Online (Sandbox Code Playgroud)
(在写我自己的lock_guard以外)有没有办法使用类似的标准std::lock_guard变体,但这将使我的!锁定!互斥(std::try_lock()上面的效果)并且当调用该守卫的d-tor时简单地将其解锁?