我正在尝试更深入地了解轻松的内存排序。根据 CPP 参考,没有同步,但是仍然保证原子性。在这种情况下,原子性是否不需要某种形式的同步,例如,fetch_add()
下面如何保证只有一个线程将值从y
to更新y+1
,特别是如果写入可以乱序对不同线程可见?是否存在与相关的隐式同步fetch_add
?
memory_order_relaxed 松弛操作:对其他读取或写入没有同步或排序约束,仅保证此操作的原子性(请参阅下面的松弛排序)
#include <thread>
#include <iostream>
#include <atomic>
#include <vector>
#include <cassert>
using namespace std;
static uint64_t incr = 100000000LL;
atomic<uint64_t> x;
void g()
{
for (long int i = 0; i < incr; ++i)
{
x.fetch_add(1, std::memory_order_relaxed);
}
}
int main()
{
int Nthreads = 4;
vector<thread> vec;
vec.reserve(Nthreads);
for (auto idx = 0; idx < Nthreads; ++idx)
vec.push_back(thread(g));
for(auto &el : vec)
el.join();
// Does not trigger
assert(x.load() == incr * Nthreads);
}