Hard
Double-checked locking with a raw pointer and a mutex
Multiple threads call getInstance() concurrently. Is this classic double-checked locking pattern correct in C++?
main.cpp
Singleton* instance = nullptr;
std::mutex mtx;
Singleton* getInstance() {
if (!instance) { // first check, no lock
std::lock_guard<std::mutex> lock(mtx);
if (!instance) { // second check, locked
instance = new Singleton();
}
}
return instance;
}13 of 51 in Concurrency