Hard
Double-checked locking singleton
This is the classic 'double-checked locking' singleton, written with a plain (non-atomic) pointer. Thread A calls instance() first and is in the middle of constructing the Singleton (inside the locked region) when Thread B calls instance() concurrently and evaluates the first, unlocked if (!instance_). Is this program correct?
singleton.cpp
#include <mutex>
class Singleton {
public:
static Singleton* instance() {
if (!instance_) { // (1) unlocked check
std::lock_guard<std::mutex> lock(mutex_);
if (!instance_) { // (2) locked check
instance_ = new Singleton(); // (3) construct + publish
}
}
return instance_;
}
private:
Singleton() = default;
static Singleton* instance_;
static std::mutex mutex_;
};
Singleton* Singleton::instance_ = nullptr;
std::mutex Singleton::mutex_;69 of 117 in C++