C++ 关于g+中原子数的检验+;4.8.1编译器

C++ 关于g+中原子数的检验+;4.8.1编译器,c++,c++11,atomic,C++,C++11,Atomic,我在winx中的MinGW中有以下测试,由以下人员编译: g++-std=c++11-DTEST2 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 #

我在winx中的MinGW中有以下测试,由以下人员编译:

g++-std=c++11-DTEST2 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 
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 
atomic_int totalx(0);
void*test_func0(void*arg)
{
#ifdef测试2

对于(i=0;iC++11标准将
atomic_XXX
定义为
std::atomic
([atomics.types.generic]p7)的
typedef
std::atomic
有一个
操作符+=(int)
,该操作符被定义为具有与
atomic_fetchadd
([atomics.types.operations.pointer]p27)相同的效果.因此,您的两个测试序列被定义为具有相同的效果

atomic\u XXX
类型用于C11兼容性-只需使用
std::atomic
,您可能会更轻松