Reputation: 159
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).
I am planning to use a "std::mutex mutex_var" to protect those variables inside the function which manipulates them. So I have the "std::mutex mutex_var" variable. 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?
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
-R
Upvotes: 0
Views: 1071
Reputation: 5027
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
. 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
So std::lock_guard
is better
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.
Upvotes: 2
Reputation: 26
Upvotes: 0