我试图了解顺序一致的排序对负载意味着什么。考虑以下人工示例:
#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_relaxed
或std::memory_order_acq_rel
,负载-负载对将不会创建同步点。 std::memory_order_seq_cst
对于负载-负载对有什么区别吗?