Std::call once
lastmod 2026-11-10created 2015-03-243 edits
std::call_once is a function in the C++11 mutex header that guarantees the callable object passed to it is executed exactly once, even if multiple threads call it simultaneously. Whether it has been executed is recorded in the std::once_flag object passed along with it; if the callable object throws an exception, it is not considered executed, and the next caller tries again. It is used for work that must be done only once, such as lazy initialization, singleton creation, or library-wide global setup; since C++11, initialization of a simple static local variable is guaranteed to be thread-safe, so that is often sufficient.
Example
#include <mutex>
// ...
static std::once_flag register_flag;
std::call_once(register_flag, [this](){
this->init();
});