简体   繁体   中英

Can atomic RMW seq_cst followed and preceded by an atomic load acquire be reordered on x86?

I have a pattern like the following:

std::atomic_uint32_t x{};
std::atomic_bool y{};

void wait_at_y()
{
    if (!y.load(std::memory_order_acquire))     // 1
        return;

    x++;  // uses seq_cst by default            // 2

    // spin until 'y' is set 'false'
    while (y.load(std::memory_order_acquire));  // 3

    x--;  // uses seq_cst by default            // 4
}

// function run by N threads
void foo()
{
    while (running)
    {
        wait_at_y();

        // do stuff
    }
}

Does wait_at_y() written this way guarantee on x86 that 1 , 2 , 3 , and 4 will get executed exactly in this order, ie without reordering any of them? If not, what is required to prevent any reordering?Atomic memory fences maybe, if yes where?

Both x, y are atomic variables, and all operation is doing in sequential consistency.

Yes , 1, 2, 3, 4 will get executed exactly in this order. You don't need to insert atomic memory fence anywhere.

But it does not guarantee that your program is correct. You can meet data races elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM