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

I can't understand weird std::atomic_short.load() behavior

本文关键字:atomic short 行为 load std      更新时间:2023-10-16

我很难理解C++11 std::atomic_short行为的一部分
我将0或255设置为atomic_short变量的值
但是.load()表示该值既不是0也不是255。
我想要一个线程来写原子变量,我想要另一个线程读取它

环境:
英特尔酷睿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! %dn", 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

问题是您有两个单独的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! %dn", i);
        }
    }
}

实例