gcc 的编译选项 -O 使用注意事项

1. 序言

我们知道gcc 的 -O 选项是用来在编译时帮我们做优化的,但是这种优化是存在一定风险的,可能会导致代码并没有按照你的意图执行

比如下面这段代码:

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

static int flag = 0;

void test()
{
    
    
    int a = 10;
    int b = 20;

    cout << a + b << endl;
}

void *task1(void *arg)
{
    
    
    while(1) {
    
    
        sleep(5);
        flag = 1;
        cout << "flag" << endl;
    }
}

void *task2(void *arg)
{
    
    
    while(1) {
    
    
        if (flag) {
    
    
            cout << "========" << endl;
            test();
        }
    }
}

int main()
{
    
    
    //int rc = -1;
    pthread_t pid;

    pthread_create(&pid, NULL, task1, NULL);
    pthread_create(&pid, NULL, task2, NULL);
    
    while(1);

    return 0;
}

看上去比较简单的一段代码,开了两个线程task1 在sleep(5)秒后使flag=1,task2一直在while(1)中读取flag的值,如果falg为真则执行里面的内容,看上去是没啥问题的,但是当编译时打开了 -O2 选项发现事情不对了,没有执行task2中flag为真后的内容,我猜测可能是编译器优化的问题,关掉优化后果然代码按顺序执行了。

2. 简单总结

优化选项的使用还是要谨慎的,更多内容可参考:
https://blog.csdn.net/qq_31108501/article/details/51842166

https://blog.csdn.net/luckywang1103/article/details/51303323

https://zhuanlan.zhihu.com/p/96001570?utm_source=wechat_session

猜你喜欢

转载自blog.csdn.net/gmq_syy/article/details/112796849
今日推荐