C++ g++;编译器-O2导致程序异常

C++ g++;编译器-O2导致程序异常,c++,c,g++,compiler-optimization,C++,C,G++,Compiler Optimization,我用g++4.8.2编译了以下源代码 #include "mpmc.hpp" #include <semaphore.h> #include <signal.h> using namespace std; mpmc_bounded_queue<std::string> mq(2048) ; volatile int counter1=0 ; volatile int counter2=0 ; #define LOOP 1000000 void gexit

我用g++4.8.2编译了以下源代码

#include "mpmc.hpp"
#include <semaphore.h>
#include <signal.h>

using namespace std;

mpmc_bounded_queue<std::string> mq(2048) ;
volatile int counter1=0 ;
volatile int counter2=0 ;
#define LOOP 1000000

void gexit(int gub)
{
    printf("(%d),(%d)\n",counter1,counter2) ;
    exit( 0 ) ;
}

int main(int argc, char* argv[])
{
    signal(SIGINT, gexit);
    signal(SIGTERM, gexit);

    void    *func1(void *);
    void    *func2(void *);
    pthread_t tid ;
    long int       icnt = 0;
    pthread_create(&tid, NULL, &func1 , (void *) icnt );
    pthread_create(&tid, NULL, &func1 , (void *) icnt );
    pthread_create(&tid, NULL, &func1 , (void *) icnt );

    pthread_create(&tid, NULL, &func2 , (void *) icnt );
    pthread_create(&tid, NULL, &func2 , (void *) icnt );

    while( 1 )
        sleep( 500 ) ;
}

void    *func2(void * inum)
{
    pthread_detach(pthread_self());
    int iret = 0 ;
    while(1){
        while( 1 ){
            std::string s ;
            if( mq.dequeue(s) ){
                iret = __sync_add_and_fetch(&counter2,1) ;
                break ;
            }else{
                usleep( 1 ) ;
                continue ;
            }
            //usleep( 10 ) ;
        }//while
    }//while
}
void    *func1(void * inum)
{
    pthread_detach(pthread_self());
    char ptr[11]={0} ;
    sprintf(ptr,"%08d",0) ;
    string s(ptr) ;

    while(1){
        while( 1 ){
            if( mq.enqueue(s) ){
                __sync_add_and_fetch(&counter1,1) ;
                break ;
            }
            usleep(100) ;
            if( counter1 >= LOOP )
                break ;
            continue ;
        }//while
        if( counter1 >= LOOP )
            break ;
        usleep(1) ;
    } //while
    printf("func1 done \n") ;
}
只有一个“func1完成”,然后按control-c打印:(1000000),(1000000)

如果我通过以下方式编译: g++--std=c++11-Werror testprint.cpp-pthread-o testprint.exe

运行它将获得以下结果:

func1 done
func1 done 
func1 done 
func1 done
所有三个“func1完成”,然后按control-c打印:(1000002),(1000002)

我认为没有-O2会更有意义,-O2也会 完成第一个“func1”需要大约45秒,但不需要-O2 只需17秒即可完成所有“功能1完成”


我可以知道g++优化器在这种情况下是如何导致这种情况发生的吗?

OT:您正在将C++和C++编译与
-s
混合,以查看在使用和不使用
-O2
@Lorehead,-s不使用-O2执行文件大小为14720,-s使用-O2执行文件大小为10600的情况下生成的代码有哪些不同搜索函数名
diff
也可能有帮助。哦,您可以尝试将对
printf()
的调用包装在互斥锁中。它不一定是线程安全的。OT:您将C和C++编译与
-s
混合使用,以查看使用和不使用
-O2
@Lorehead,-s不使用-O2执行文件大小为14720,-s使用-O2执行文件大小为10600搜索函数名
diff
也可能有帮助。哦,您可以尝试将对
printf()
的调用包装在互斥锁中。它不一定是线程安全的。