簡體   English   中英

我無法理解奇怪的std :: atomic_short.load()行為

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

我無法理解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

問題是你有兩個單獨的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);
        }
    }
}

實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM