m.e*_*ahi 2 c++ optimization g++ clang++
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我用以下命令编译上面的代码时,一切都很好:
$ g++ test.cpp -lpthread -std=c++11
$ clang++ test.cpp -lpthread -std=c++11
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用优化标志时,我的程序没有完成.我测试了以下所有命令:
$ 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
Run Code Online (Sandbox Code Playgroud)
我的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
Run Code Online (Sandbox Code Playgroud)
不可以.C和C++内存模型不允许非原子变量的跨线程交互,或者不受互斥锁/锁保护.这是一场数据竞赛并且违反了抽象机器,因此优化器完全有权发布Nethack.
编写优化器时假设,如标准明确允许的那样,外部源(包括其他线程)无法在没有用户明确控制的情况下神奇地改变程序的状态.