|
|
|
|
|
by vinkelhake
4510 days ago
|
|
The real advantage of a scoped lock is that it promises to release the mutex, no matter how the scope is exited. If this LOCKED macro is used and an exception is thrown from within the block, that mutex now stays locked. > The only gotcha is, there is some overhead involved in this approach. The class instance takes up some space on the stack (several bytes) for every lock acquisition. Not so fast. A decent compiler will eliminate the overhead and not actually allocate stack space for the lock. Here's an example using one of the lock guards in C++: struct foo {
int var;
std::mutex m;
};
void process1(foo& f) {
std::lock_guard<std::mutex> lock(f.m);
++f.var;
}
void process2(foo& f) {
f.m.lock();
++f.var;
f.m.unlock();
}
GCC 4.8.1 generates identical code for process1 and process2. |
|
(1) avoids best practice (RAII) using...
(2) a flawed rationale (ignoring the existence of compiler optimizations)...
(3) without measurement to demonstrate the supposed flaw in the best practice (which would have surfaced the flawed rationale)...
(4) and therefore implements a micro-optimization with no actual win...
(5) and introduces a bug in the process (it's not exception safe).