Hard
Double-checked locking over a std::atomic pointer
This lazy initializer is correct as written: callers dereference the returned pointer and read p->path and p->retries with no further synchronization. Which single change keeps every one of those reads free of data races?
main.cpp
struct Config { std::string path; int retries; };
std::atomic<Config*> g_cfg{nullptr};
std::mutex g_mtx;
Config* get() {
Config* p = g_cfg.load(std::memory_order_acquire); // (A)
if (!p) {
std::lock_guard<std::mutex> lk(g_mtx);
p = g_cfg.load(std::memory_order_acquire); // (B)
if (!p) {
p = new Config{"/etc/app.conf", 3};
g_cfg.store(p, std::memory_order_release); // (C)
}
}
return p;
}45 of 51 in Concurrency