小编peb*_*888的帖子

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

我无法理解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);
        } …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

3
推荐指数
1
解决办法
116
查看次数

标签 统计

c++ ×1

c++11 ×1