Back to questionsWhere, if anywhere, does the call
JuniorTheoryCommon
Where, if anywhere, does the call add(-1) unlock the mutex m?
#include <mutex>
std::mutex m;
int total = 0;
void add(int x) {
std::lock_guard<std::mutex> guard(m);
if (x < 0) {
return;
}
total += x;
}At return;, where guard goes out of scope and its destructor runs
- Expecting
return;to skip the unlock: the destructor ofguardruns on every exit from its scope, an earlyreturnincluded. - Expecting to have to call
m.unlock()by hand: the destructor oflock_guardunlocksm, and that is the reason to use it.
- Why is
lock_guardsafer than callingm.lock()andm.unlock()by hand? - How would you keep
mlocked for only part of a function?