use*_*874 5 c++ future compiler-bug c++11
我有一个C++ 11程序,检查一个数字是否为素数.程序等待准备就绪的未来对象.准备就绪后,程序会告诉未来对象的提供者功能是否认为该数字是素数.
// future example
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
const int number = 4; // 444444443
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call function asynchronously:
std::future<bool> fut = std::async (is_prime, number);
// do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span (100);
//std::chrono::duration<int> span (1);
while (fut.wait_for(span)==std::future_status::timeout) {
std::cout << '.';
std::cout.flush();
}
bool x = fut.get(); // retrieve return value
std::cout << "\n"<<number<<" " << (x?"is":"is not") << " prime.\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果运行该程序,您将看到它处于无限循环中,因为wait_for()始终返回future_status::timeout,这意味着共享状态永远不会准备好.这是什么原因?我从http://www.cplusplus.com/reference/future/future/wait_for/上获取了这个程序,所以我希望它可以工作.但是,如果我注释掉while循环,程序将正常工作.
代码正在运行:(g ++ 4.9,clang 3.4)http://coliru.stacked-crooked.com/a/f3c2530c96591724
我使用MINGW32和g ++ 4.8.1获得了与你相同的行为.明确设置策略以std::launch::async解决问题.
(即:std::async(std::launch::async, is_prime, number);)