以下函数是否总是在写入 y[100] 之前写入 x[100]?
void fenceTest(float * x, float * y /* this could be x too*/)
{
x[100]=3.14f; // maybe atomic write
x[200]=3.14f;
myMutex.lock();
myMutex.unlock();
y[100]=2.72f; // maybe atomic write too
y[200]=2.72f;
}
或者即使对于这种单线程场景,也总是需要在端点之后解锁互斥锁,还是我们必须使用 atomic_thread_fence?
void fenceTest(float * x, float * y)
{
x[100]=3.14f; // maybe atomic too
x[200]=3.14f;
std::atomic_thread_fence(std::memory_order_relaxed);
y[100]=2.72f; // maybe atomic write too
y[200]=2.72f;
}
我的目的是告诉 CPU 和编译器,它们不允许在同步点周围重新排序任何加载/存储,以便在任何 y 数组操作开始之前完成所有 x 数组操作。我需要分离读/写块,以便像Kahan-Summation这样的算法不会被编译器或 CPU 的重新排序破坏。