codeworks
codeworks

Reputation: 159

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).

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

Answers (2)

Superlokkus
Superlokkus

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

Nemo Vu
Nemo Vu

Reputation: 26

  • With the simple mutex, if all the threads are reading thread, you don't need to lock the resource. But if there are one or more among the threads writing to the recourse, you need to lock from all threads even the reading ones.
  • There is a way to avoid locking resources, when there is no writing threads and lock the resources when the is one writing thread. You need to use a more complex locking mechanism, you should be reading about openforread and openforwrite logic.

Upvotes: 0

Related Questions