Reputation: 102346
The CPP Reference states std::call_once
is thread safe:
Executes the function f exactly once, even if called from several threads.
Will I need to use memory barriers when utilizing lazy initialization if the code runs on a machine with multiple physical processors (as opposed to a single processor with multiple cores)? For example:
static Foo& GetFooRef()
{
static std::once_flag flag;
static Foo foo;
MEMORY_BARRIER();
std::call_once(flag, []() {
Foo f = ...;
foo.swap(f);
});
MEMORY_BARRIER();
return foo;
}
Where MEMORY_BARRIER()
is
_ReadWriteBarrier()
for MSVC,__asm__ __volatile__ ("" ::: "memory")
for GCC,__memory_barrier()
for ICC, etc.Upvotes: 1
Views: 968
Reputation: 1951
Yes, this is the whole point of call_once
. Thread-safe means on the same or different processors, on an ordinary machine with shared memory.
Upvotes: 10