cppreference says that std::memory_order_acquire will prevent read and write from reordering before it. So I can use std::memory_order_acquire just for preventing from reorder at run-time without corresponding std::memory_order_release. For example

#include <atomic>
#include <stdint.h>

std::atomic<uint32_t> g_counter{};//Counter for thread in Fun
std::atomic<void*> g_data{};
void Fun()
{
    g_counter.fetch_add(1, std::memory_order_acquire);//Warning:`fetch_add` maybe reorder after next 'load'
    void *data = g_data.load(std::memory_order_acquire);
    g_counter.fetch_sub(1, std::memory_order_relaxed);//just memory_order_relaxed will be ok
}

Is that true?

1 Answers

0
water On Best Solutions

After a couple of days learning. I think 'release' and 'acuire' can be used separately to prevent corresponding reordering . But there is something wrong with the example. That is a store operation about 'fetch_add' , and the store maybe reorder after the next load. The right way is change both of the fetch_add and next load to be memory_order_seq_cst operation.