Willy
Willy

Reputation: 581

Is memory fence needed after joining another thread without any lock?

I am wondering if I need to put a memory fence after thread join if I want to read values stored from that thread immediately. Does thread join already imply a memory fence?

vector<int> v(1 << 21);

thread th([&]() {
    for (int i = 0; i < (1 << 20); i++) {
        v[i] = i * 123; // store some kind of calculation results into the vector
    }
});

for (int i = (1 << 20); i < (1 << 21); i++) {
    v[i] = i * 123;
}

th.join();

// Is any memory fence needed to be here?

// use the values from another thread... 
printf("%d\n", v[1234]);
// ...

Upvotes: 2

Views: 96

Answers (1)

Felix Glas
Felix Glas

Reputation: 15524

No. No memory fence is needed, as thread::join will block until the thread of execution has finished executing. Also, the join operation is executed by the main thread after running the loop. I don't see how a fence would be needed following the join operation.

Upvotes: 1

Related Questions