C++ 11使用非原子变量的原子内存顺序

Jef*_*zza 6 c++ multithreading atomic memory-barriers c++11

我不确定c ++ 11中的原子变量的内存排序保证如何影响对其他内存的操作.

假设我有一个线程周期性地调用write函数来更新一个值,另一个线程调用read来获取当前值.是否保证在效果d = value;之前不会看到效果a = version;,并且会在效果之前看到b = version;

atomic<int> a {0};
atomic<int> b {0};
double d;

void write(int version, double value) {
    a = version;
    d = value;
    b = version;
}

double read() {
    int x,y;
    double ret;
    do {
        x = b;
        ret = d;
        y = a;
    } while (x != y);
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

Tsy*_*rev 0

是否保证 的效果d = value;不会在 的效果之前看到a = version;,并且会在 的效果之前看到b = version;

是的。这是因为在读取或写入变量时隐含了顺序一致性屏障atomic<>

您可以在修改之前和之后递增单个原子变量,而不是在值修改之前和之后将version标记存储到两个原子变量中:

atomic<int> a = {0};
double d;

void write(double value)
{
     a = a + 1; // 'a' become odd
     d = value; //or other modification of protected value(s)
     a = a + 1; // 'a' become even, but not equal to the one before modification
}

double read(void)
{
     int x;
     double ret;
     do
     {
         x = a;
         ret = value; // or other action with protected value(s)
     } while((x & 2) || (x != a));
     return ret;
}
Run Code Online (Sandbox Code Playgroud)

这在 Linux 内核中称为seqlock :http: //en.wikipedia.org/wiki/Seqlock