顺序一致的原子负载(负载-负载对)形成线程间同步点吗?

时间:2018-07-28 20:21:07

标签: c++ c++11 atomic

我试图了解顺序一致的排序对负载意味着什么。考虑以下人工示例:

#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, std::memory_order_relaxed);
}

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

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

assert会失败吗?要么 counter.fetch_add()counter.load()同步吗?

据我了解,对counter进行的操作具有std::memory_order_relaxedstd::memory_order_acq_rel,负载-负载对将不会创建同步点。 std::memory_order_seq_cst对于负载-负载对有什么区别吗?

0 个答案:

没有答案