jww
jww

Reputation: 102346

Is std::call_once multi-processor safe?

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

Upvotes: 1

Views: 968

Answers (1)

Herb Sutter
Herb Sutter

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

Related Questions