我是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
(在写我自己的lock_guard之外)有没有办法使用类似的&amp;标准的std::lock_guard
变体,但是我的锁定!互斥(上面std::try_lock()
的效果)并且在调用该守卫的d-tor时将其解锁?
答案 0 :(得分:6)
使用此:
// now ensure this will get called only once per event
if (_mutex.try_lock())
{
std::lock_guard<std::mutex> guard(_mutex, std::adopt_lock);
// critical section
} // mutex will be unlocked here
更新并且不要使用以下划线开头的变量名称(_mutex
)。
答案 1 :(得分:2)
通过此信息,您可以看到,如果您指定第二个参数,例如此std::lock_guard<std::mutex> guard(_mutex, std::try_to_lock)
,则行为会更改为std::try_lock
而不是std::lock