I want to do roughly this:
Initial thread:
std::atomic<>
.Other threads:
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?
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With