jeudi 27 avril 2017

Cache coherence on atomic variable

std::atomic_bool flag{false};
int data{0};

void sendRequest()
{
    // send request over network
}

bool replyReceived()
{
    // return true when reply is received over the network, false otherwise
}

void threadA()
{
    data = 123;
    flag.store(true, std::memory_order_seq_cst);  // (1)
    sendRequest();
}

void threadB()
{
    while (!replyReceived())
    {
    }
    if (flag.load(std::memory_order_acquire))  // (2)
    {
        // processing on data (3)
    }
}

In the above listing, threadA() and threadB() are run by different threads. threadA() sends a network request whereas threadB() receives the reply of the request. flag is an atomic variable to ensure that new value of data is observed in (3). My question is should (2) always evaluate to true? Is it possible for it to be false even though (1) must have been executed before (2) in real time? The platform is x86.

Aucun commentaire:

Enregistrer un commentaire