Hard
A hand-rolled double-checked-locking singleton
This hand-rolled double-checked-locking singleton predates std::call_once and magic statics thinking, written the way it was commonly (and incorrectly) done pre-C++11, but compiled with a modern optimizing C++17 compiler with no extra synchronization added. Two threads call instance() for the first time concurrently. What can happen?
main.cpp
class Widget {
public:
static Widget* instance() {
if (ptr_ == nullptr) { // 1st check, no lock
std::lock_guard<std::mutex> lk(mtx_);
if (ptr_ == nullptr) { // 2nd check, locked
ptr_ = new Widget();
}
}
return ptr_;
}
int value = 42;
private:
static Widget* ptr_;
static std::mutex mtx_;
};
Widget* Widget::ptr_ = nullptr;
std::mutex Widget::mtx_;3 of 44 in Design Patterns