我编写了一个简单的多线程程序,如下所示:
static bool finished = false;
int func()
{
size_t i = 0;
while (!finished)
++i;
return i;
}
int main()
{
auto result=std::async(std::launch::async, func);
std::this_thread::sleep_for(std::chrono::seconds(1));
finished=true;
std::cout<<"result ="<<result.get();
std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}
在Visual Studio的调试模式或者gcc中的-O0
模式下,程序运行正常,并会在1
秒后输出结果。但在Release模式或者-O1 -O2 -O3
模式下,程序停滞不前,无法输出任何信息。