Search code examples
c++c++11futurecompiler-bug

C++11 future.wait_for() always returns future_status::timeout


I have a C++11 program that checks whether a number is prime. There is a future object that the program waits for to be ready. After it is ready, the program tells whether a a provider function of future object considered the number to be prime.

// 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;
}

If you run the program, you will see that it is in an infinite while loop, since wait_for() always returns future_status::timeout, which means that the shared state is never ready. What is the reason for that? I took this program from http://www.cplusplus.com/reference/future/future/wait_for/, so I expected it to work. However, if I comment out the while loop, the program will work fine.


Solution

  • The code is working: (g++ 4.9, clang 3.4) http://coliru.stacked-crooked.com/a/f3c2530c96591724

    I get the same behavior as you with MINGW32 with g++ 4.8.1 though. Setting the policy explicitly to std::launch::async solves the issue.
    (i.e: std::async(std::launch::async, is_prime, number);)