【问题标题】:I can't understand weird std::atomic_short.load() behavior我无法理解奇怪的 std::atomic_short.load() 行为
【发布时间】:2016-12-05 15:27:15
【问题描述】:

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

环境:
英特尔酷睿 i5
OSX 10.11.6
铿锵声(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

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    问题是您有 2 个单独的 loads,这使得您的比较不是原子的。相反,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);
            }
        }
    }
    

    live example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2020-06-11
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多