2016-07-31 74 views
3

我無法理解C++ 11 std :: atomic_short行爲的一部分。
我設置0或255作爲atomic_short變量的值。
但.load()表示該值不是0或255.
我想要一個線程寫入原子變量,並且我希望另一個線程讀取它。我無法理解奇怪的std :: atomic_short.load()行爲

環境:
Intel酷睿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 

回答

8

的問題是,你有2個個人load S的使你的比較是非原子的。相反,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