Does spawning a thread provide memory order guarantees on its own?

Viewed 1393

I want to do roughly this:

Initial thread:

  • write some values to global vars (they will never be written again)
    • This could be moderately large data (arrays, strings, etc). Cannot simply be made std::atomic<>.
  • spawn other threads

Other threads:

  • read the global state
  • do work, etc.

Now, I know I can pass arguments to std::thread, but I'm trying to understand the memory guarantees of C++ through this example.

Also, I am pretty confident that on any real-world implementation, creating a thread will cause a memory barrier ensuring that the thread can "see" everything the parent thread wrote up until that point.

But my question is: is this guaranteed by the standard?

Aside: I suppose I could add some dummy std::atomic<int> or so, and write to that before starting the other threads, then on the other threads, read that once on startup. I believe all the happens-before machinery would then guarantee that the previously-written global state is properly visible.

But my question is if something like that is technically required, or is thread creation enough?

1 Answers

Thread creation is enough. There is a synchronization point between the thread constructor and the start of the new thread per [thread.thread.constr]/6

Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

This means that all state in the thread before the new thread is spawned is visible to the spawned thread.

Related