samedi 28 juillet 2018

do sequentially-consistent atomic loads (load-load pair) form an inter-thread synchronisation point?

I am trying to understand what does sequentially-consistent ordering mean for loads. Consider this artificial example:

#include <atomic>
#include <thread>
#include <cassert>

static std::atomic<bool> preStop {false};
static std::atomic<bool> stop {false};
static std::atomic<int> counter{0};

void waiter() {
    preStop.store(true, std::memory_order_relaxed);
    while (counter.load() > 0);
    stop.store(true);
}

void performer() {
    while (true) {
        counter.fetch_add(1);
        if (stop.load()) {
            assert(preStop.load());
            return;
        }
        counter.fetch_sub(1);
        std::this_thread::yield();
    }
}

int main() {
    std::thread performerThread(performer);
    std::thread waiterThread(waiter);
    waiterThread.join();
    performerThread.join();
}

Can assert fail? Or does counter.fetch_add() synchronise with counter.load()?

It is my understanding that had operations on counter have std::memory_order_relaxed or std::memory_order_acq_rel, the load-load pair would not create a synchronisation point. Does std::memory_order_seq_cst makes any difference for load-load pairs?

Aucun commentaire:

Enregistrer un commentaire