Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including std::lock_guard in extra scope

Tags:

c++

mutex

locking

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?

like image 202
KabCode Avatar asked Jan 28 '19 10:01

KabCode


People also ask

What additional behavior does a lock_guard provide over a mutex?

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.

What is the role of std :: lock_guard?

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.

Are lock guards deprecated?

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

Should lock_guard be const?

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.


1 Answers

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.

like image 131
Angew is no longer proud of SO Avatar answered Oct 11 '22 05:10

Angew is no longer proud of SO