我无法理解奇怪的std :: atomic_short.load()行为

3
我在理解C++11 std::atomic_short行为的某一部分时遇到了问题。
我将0或255设置为一个atomic_short变量的值,但是.load()方法显示其值既不是0也不是255。
我希望一个线程写入这个原子变量,而另一个线程读取它。

环境:
Intel Core i5
OSX 10.11.6
clang (Xcode7.3.1)

#include <iostream>
#include <atomic>
#include <thread>

std::atomic_short value = ATOMIC_VAR_INIT(0);

void process1() {
    bool flag = false;
    for (int i = 0; i < 100000; ++i){
        std::this_thread::yield;
        if (flag){
            value.store(255);
        } else {
            value.store(0);
        }
        flag = !flag;
    }
}

void process2() {
    for (int i = 0; i < 100000; ++i){
        std::this_thread::yield;
        if (value.load() != 255 && value.load() != 0){
            printf("warningA! %d\n", i);
        }
    }
}

int main(int argc, char** argv) {
    value.store(0);
    std::thread t1(process1);
    std::thread t2(process2);
    t1.join();
    t2.join();

    return 0;
}

warningA! 3
warningA! 1084
warningA! 1093
1个回答

8
问题在于你有两个独立的load,这使得你的比较不是原子性的。相反,只需一次load值,然后进行比较:
void process2() {
    for (int i = 0; i < 100000; ++i){
        std::this_thread::yield;
        auto currentValue = value.load();
        if (currentValue != 255 && currentValue != 0){
            printf("warningA! %d\n", i);
        }
    }
}

实时演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接