[英]Whats better std::lock_guard<std::mutex> lock(std::mutex mutex_var); or std::mutex mutex_var.lock();
I need to lock operations of a std::map and two boost::multimaps inside a function since we have threads trying to access the function(and thus the maps). 我需要在一个函数中锁定std :: map和两个boost :: multimaps的操作,因为我们有线程试图访问该函数(因此也访问了这些映射)。
I am planning to use a "std::mutex mutex_var" to protect those variables inside the function which manipulates them. 我打算使用“ std :: mutex Mutex_var”来保护操作它们的函数中的那些变量。 So I have the "std::mutex mutex_var" variable. 因此,我有“ std :: mutex Mutex_var”变量。 I am confused between using "mutex_var.lock()" in the beginning of the function and "mutex_var.unlock()" in the end of the function (OR) just use std::lock_guard in just the beginning of the function? 我对在函数开头使用“ mutex_var.lock()”和在函数末尾使用“ mutex_var.unlock()”(或)感到困惑,只是在函数开头使用std :: lock_guard?
For clarity all the function does is adding things on the mutex. 为了清楚起见,所有功能所做的就是在互斥锁上添加内容。 I also understand/thing that we dont need to guard all the places where we try to query the map(since it is only a read operation). 我也了解/不需要保护所有试图查询地图的地方(因为这只是读取操作)。
Please let me know the better alternative, and, also please clarify if my thought of reading does not need protection is correct. 请让我知道更好的选择,并且,请澄清我的阅读思想是否不需要保护是正确的。
TIA TIA
-R -R
You should (almost) never use std::mutex::lock()
, std::mutex::try_lock()
or std::mutex::unlock()
directly, always use a std::lock_guard
or std::unique_lock
with your mutex_var
. 您应该(几乎) 永远不要直接使用 std::mutex::lock()
, std::mutex::try_lock()
或std::mutex::unlock()
,始终使用std::lock_guard
或std::unique_lock
与您的mutex_var
。 Because you don't have to write unlock, because they are doing it when they are destroyed. 因为您不必编写解锁,因为它们在销毁时正在这样做。 So you can't forget it, even if a exception has been thrown in the mean time. 因此,即使在此期间引发了异常,您也不会忘记它。 This is called RAII and is what you want for modern C++ code 这称为RAII ,这是现代C ++代码所需要的
So std::lock_guard
is better 所以std::lock_guard
更好
And for 而对于
I also understand/thing that we dont need to guard all the places where we try to query the map 我也了解/不需要我们保护所有试图查询地图的地方
Usually you still have to guard that read operation, because you don't know when someone wants to write. 通常,您仍然必须保护读取操作,因为您不知道何时有人要写入。 But it depends on your design, the whole problems is known as readers-writer-problem and since you seem to be unaware of that, I assume your design needs locking for all steps. 但这取决于您的设计,整个问题被称为读者-作家-问题 ,由于您似乎没有意识到这一点,因此我认为您的设计需要锁定所有步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.