std::lock_guard() for a locked std::mutex

社会主义新天地 提交于 2020-12-10 06:46:32

问题


I am new to C++11 threading.

The following piece of code should be executed only by the first thread.

The other threads (which might race with the first thread) should not enter the locked code area (that's why the std::try_lock() is there).

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        

(Outside from writing my own lock_guard) Is there a way to use a similar & standard std::lock_guard variant, but which will take my !locked! mutex (effect of std::try_lock() above) and simply unlock it when the d-tor of that guard will be called?


回答1:


Have a look at this

and this

From this info you can see that if you specify a second parameter like this std::lock_guard<std::mutex> guard(_mutex, std::try_to_lock) the behaviour is changed to act like std::try_lock rather than std::lock




回答2:


Use this:

// 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

Update And don't use variable names starting with underscore (as _mutex).



来源:https://stackoverflow.com/questions/25033453/stdlock-guard-for-a-locked-stdmutex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!