vendredi 5 juin 2020

According to C++ memory model, are reads automatically synchronized between threads?

Consider the following example:

int main() 
{
    int x = 0;

    std::atomic_thread_fence(std::memory_order_seq_cst);

    x = 5;

    std::thread t([&]() {
        std::cout << x << std::endl; // will this print 0 or 5 according to C++ memory model?
    });

    t.join();
}

Code on Coliru.

As you see, the result is 5. I understand this could be the case because of cache invalidation in Intel CPUs. But is this part of the C++ memory model?

Do we have an answer from the C++ standard?

Edit: It seems that the C++ standard forces synchronization when a thread is constructed. This kind of sabotages the purpose of my question, because the case I have is a thread-pool (boost::asio::io_context to be exact) where we push functions to it, that, for the case of this example, read x in other threads. So to rephrase my question: Will the other threads in the thread-pool always see the same value for x after posting the function (instead of constructing std::thread in my example above)?

Aucun commentaire:

Enregistrer un commentaire