This is exactly the type of situation for which atoms are intended. By storing the result in atomic, you know that the compiler cannot sort any critical stores or operations after the atom is installed. Atomics both for emitting primitives of processor instructions to ensure the necessary consistent consistency (for example, for cache coherency across all cores), and for the compiler, which should preserve the semantics (and, therefore, limit the types of reordering that it can perform). If you use atomic here, it doesn't matter if the function is enabled, because any compiler insert will have to preserve the semantics of the atom itself.
You may also be interested in searching in std::call_once , which is also designed for this situation, or rather, for a situation where several threads can do something, but just one of them should do it.
Adam H. Peterson
source share