Does is make sense to do something like putting a std::lock_guard
in an extra scope so that the locking period is as short as possible?
Pseudo code:
// all used variables beside the lock_guard are created and initialized somewhere else ...// do something { // open new scope std::lock_guard<std::mutex> lock(mut); shared_var = newValue; } // close the scope ... // do some other stuff (that might take longer)
Are there more advantages besides having a short lock duration?
What might be negative side effects?
The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block. When a lock_guard object is created, it attempts to take ownership of the mutex it is given.
std::lock_guard A lock guard is an object that manages a mutex object by keeping it always locked. On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked.
And that's why lock_guard isn't deprecated. scoped_lock and unique_lock may be a superset of functionality of lock_guard , but that fact is a double-edged sword. Sometimes it is just as important what a type won't do (default construct in this case).
A const instance of std::lock_guard behaves identically to a non- const one. There is no benefit to adding the const , nor to omitting it. The type has no member functions, and is not copyable or movable, so there is essentially no difference at all. I would consider the const as noise and remove it.
Yes, it certainly makes sense to limit the scope of lock guards to be as short as possible, but not shorter.
The longer you hold a lock, the more likely it is that a thread will block waiting for that lock, which impacts performance as is thus usually considered a bad thing.
However, you must make sure that the program is still correct and that the lock is held at all times when it must be, i.e. when the shared resource protected by the lock is accessed or modified.
There may be one more point to consider (I do not have enough practical experience here to speak with certainty). Locking/releasing a mutex can potentially be an operation with nontrivial performance costs itself. Therefore, it may turn out that keeping a lock for a slightly longer period instead of unlocking & re-locking it several times in the course of one operation can actually improve overall performace. This is something which profiling could show you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With