Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 876
jwd Avatar asked Feb 26 '20 22:02

jwd


People also ask

What is Memory_order_acquire?

memory_order_acquire: Syncs reading this atomic variable AND makes sure relaxed vars written before this are synced as well. (does this mean all atomic variables on all threads are synced?) memory_order_release: Pushes the atomic store to other threads (but only if they read the var with consume/acquire)

How do I notify a specific thread in C++?

If you want to notify a specific thread, use a separate std::condition_variable for it. Do not use that std::condition_variable for other threads.


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]/7

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.

like image 96
NathanOliver Avatar answered Sep 22 '22 16:09

NathanOliver