这是g++和clang++优化的bug吗?

Is it a bug for g++ and clang++ optimization?

本文关键字:bug 优化 g++ clang++ 这是      更新时间:2023-10-16
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
bool m_ok = false;
void* run(void*)
{
    usleep(1000000);
    m_ok = true;
    printf ("Good bye!n");
    return nullptr;
}   
int main() {
    pthread_t my_thread;
    pthread_create(&my_thread, nullptr, &run, nullptr);
    while (!m_ok)
        continue;
    printf("YES!!!n");
    return 0;
}

当我用以下命令编译上面的代码时,一切正常:

$ g++ test.cpp -lpthread -std=c++11
$ clang++ test.cpp -lpthread -std=c++11

但是当我尝试使用优化标志时,我的程序没有完成。我测试了以下所有命令:

$ g++ test.cpp -lpthread -std=c++11 -O1
$ clang++ test.cpp -lpthread -std=c++11 -O1
$ g++ test.cpp -lpthread -std=c++11 -O2
$ clang++ test.cpp -lpthread -std=c++11 -O2

我的g++和clangs的版本是:

$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ clang++ --version
Debian clang version 3.2-7ubuntu1 (tags/RELEASE_32/final) (based on LLVM 3.2)
Target: x86_64-pc-linux-gnu
Thread model: posix

No。C和c++内存模型不允许非原子变量的跨线程交互,或者在没有互斥锁保护的情况下。这是一场数据竞赛,违反了抽象机器,所以优化器完全有权利启动《Nethack》。

优化器的编写假定,正如标准明确允许的那样,外部源(包括其他线程)不能在没有用户显式控制的情况下神奇地改变程序的状态。