Medium
A locked method calling a helper that locks the same mutex
doWork() locks the object's mutex, then calls helper(), which is also a method of the same object and also locks the same mutex. Both calls happen on the same thread, and as written mtx is a std::mutex. What happens when doWork() is called, and how (if at all) would replacing std::mutex with std::recursive_mutex change the outcome?
main.cpp
class Widget {
public:
void doWork() {
std::lock_guard<std::mutex> lock(mtx);
// ... some work ...
helper(); // same thread, same object
}
void helper() {
std::lock_guard<std::mutex> lock(mtx); // locking mtx again!
// ... more work ...
}
private:
std::mutex mtx;
};34 of 51 in Concurrency