[英]A test about atomic_int in g++ 4.8.1 compiler
I have the following test in MinGW in my winx , compiled by : 我在winx中的MinGW中进行了以下测试,编译如下:
g++ -std=c++11 -DTEST2 testatomic1.cpp -lpthread -o testatomic1.exe g ++ -std = c ++ 11 -DTEST2 testatomic1.cpp -lpthread -o testatomic1.exe
g++ -std=c++11 -DTEST4 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
This test run many times in TEST2 and TEST4 defined , and answer are 300000000 all , in TEST4 , it works as I expect , TEST2 is strange to me , totalx += 1 ; 该测试在TEST2和TEST4定义的程序中运行了多次,答案总共是300000000,在TEST4中,它符合我的预期,TEST2对我来说很奇怪,totalx + = 1; without any memory model , can produce the right answer ...then why bother has load , store function ? 没有任何内存模型,可以产生正确的答案...那么,为什么要麻烦具有加载,存储功能? just define an atomic_int var will do the job right , I wonder it is too easy ... Am I miss something ? 只需定义一个atomic_int var就能正确地完成工作,我想这太容易了...我错过了什么吗?
The C++11 standard defines atomic_XXX
as a typedef
of std::atomic<XXX>
([atomics.types.generic] p7). 在C ++ 11标准定义atomic_XXX
作为typedef
的std::atomic<XXX>
([atomics.types.generic] P7)。 std::atomic<int>
has an operator+=(int)
that is defined to have the same effects as atomic_fetch_add
([atomics.types.operations.pointer] p27). std::atomic<int>
具有一个operator+=(int)
,该operator+=(int)
定义为具有与atomic_fetch_add
相同的效果([atomics.types.operations.pointer] p27)。 So your two test sequences are defined to have identical effects. 因此,您定义的两个测试序列具有相同的效果。
The atomic_XXX
types are for C11 compatibility - you may have an easier time simply using std::atomic<XXX>
. atomic_XXX
类型用于C11兼容性-使用std::atomic<XXX>
可能会更轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.