c++multithreadingc++20memory-model

Inter-thread synchronization with one atomic variant


std::atomic<int> counter = 0; // memory_order_seq_cst
int globalInt1;
int globalInt2;
int globalInt3;

void thread1()
{
    // ++counter;
    globalInt1 = 1;
    --counter;
    Wait();
}

void thread2()
{
    //++counter;
    globalInt2 = 2;
    --counter;
    Wait();
}

void thread3()
{
    // ++counter;
    globalInt3 = 3;
    --counter;
    Wait();
}


int main()
{
    ++counter;
    ++counter;
    ++counter;

    std::thread{ thread1 }.detach();
    std::thread{ thread2 }.detach();
    std::thread{ thread3 }.detach();

    while (counter != 0);

    // Can I get the value of globalInt1~3 correctly here?
}

Hi all. My question is whether I can get globalInt1~3 correctly in main thread, or the main thread can only synchronization with a certain thread that last modified the counter variable?


Solution

  • Yes, you will read globalInt1~3 correctly, This is handled by the concept of a release sequence.

    If an atomic is modified by multiple threads and you read the sum of their modifications then anything that happened in those threads before the modification will be visible to the reader after the result is loaded.

    For your example you need the modifications to use at least release order, and the reader to use acquire order, you don't need sequentially consistent order here.