Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ memory semantics and globals that are set at the start of a program

If I have one thread, the "main" thread, initialize a global variable and that thread later spawns some threads that access that variable, do I need to do any work, such as a call to std::atomic_thread_fence(memory_order_seq_cst), to guarantee that the variable appears initialized to the new threads? I suspect that the fact that the main thread creates the new threads establishes a "synchronized-with" relationship that is sufficient to prevent any races, but I'm not certain.

Here's some pseudocode for what I'm describing:

class MyApi {
public:
    static void init(Foo *foo) {
        MyApi::foo = foo;
    }

    static Foo* getSharedFoo() {
        return foo;
    }

private:
    static Foo* foo;
};

void main() {
    Foo* foo = new Foo();
    MyApi::init(foo);
    // Spawn threads that will call MyApi::getSharedFoo() and expect
    // to receive the same foo that is created above.
}
like image 626
Christopher Simmons Avatar asked Jan 24 '26 11:01

Christopher Simmons


1 Answers

No, you don't have to do anything special. New threads see all memory changes up to the point where they were constructed.

like image 79
Pete Becker Avatar answered Jan 26 '26 23:01

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!