Medium
std::call_once with a std::once_flag for lazy initialization
Eight threads all call getInstance() concurrently for the first time. initInstance() does real work (allocating and constructing an object). Using std::call_once with a std::once_flag as shown, how many times does initInstance() actually run, and what (if anything) must the caller do about memory ordering to safely read instance afterward?
main.cpp
std::once_flag initFlag;
Singleton* instance = nullptr;
void initInstance() {
instance = new Singleton();
}
Singleton* getInstance() {
std::call_once(initFlag, initInstance);
return instance; // no atomics, no memory_order, no mutex visible here
}40 of 51 in Concurrency