によってコンパイルされた、私の winx の MinGW で次のテストがあります。
g++ -std=c++11 -DTEST2 testatomic1.cpp -lpthread -o testatomic1.exe
g++ -std=c++11 -DTEST4 testatomic1.cpp -lpthread -o testatomic1.exe
atomic_int totalx(0);
void *test_func0(void *arg)
{
#ifdef TEST2
for(i=0;i<100000000;++i){
totalx += 1 ;
}//for
#endif
#ifdef TEST4
for(i=0;i<100000000;++i){
atomic_fetch_add(&totalx, 1);
}//for
#endif
}
int main(int argc, const char *argv[])
{
pthread_t id[3];
int iCPU =1 ;
pthread_create(&id[0],NULL,test_func0,(void *)(long)iCPU );
pthread_create(&id[1],NULL,test_func0,(void *)(long)iCPU );
pthread_create(&id[2],NULL,test_func0,(void *)(long)iCPU );
int i ;
for(i=0;i<3;++i){
pthread_join(id[i],NULL);
}
#ifdef TEST2
cout << "TEST2 totalx=" << totalx << endl ;
#endif
#ifdef TEST4
cout << "TEST4 totalx=" << totalx << endl ;
#endif
}//main
このテストは、定義された TEST2 と TEST4 で何度も実行され、答えはすべて 300000000 です。TEST4 では、期待どおりに動作します。TEST2 は私には奇妙です。メモリモデルがなくても正しい答えを生成できます...では、なぜわざわざロード、ストア機能があるのでしょうか? atomic_int var を定義するだけでうまくいきますが、簡単すぎるのではないかと思います...何か見逃していますか?