fork download
  1. // future::wait_for
  2. #include <iostream> // std::cout
  3. #include <future> // std::async, std::future
  4. #include <chrono> // std::chrono::milliseconds
  5.  
  6. // a non-optimized way of checking for prime numbers:
  7. bool is_prime (int x) {
  8. for (int i=2; i<x; ++i) if (x%i==0) return false;
  9. return true;
  10. }
  11.  
  12. int main ()
  13. {
  14. // call function asynchronously:
  15. std::future<bool> fut = std::async (is_prime,700020007);
  16.  
  17. // do something while waiting for function to set future:
  18. std::cout << "checking, please wait";
  19. std::chrono::milliseconds span (0);
  20. while (fut.wait_for(span)==std::future_status::timeout)
  21. std::cout << '.';
  22.  
  23. bool x = fut.get();
  24.  
  25. std::cout << "\n700020007 " << (x?"is":"is not") << " prime.\n";
  26.  
  27. return 0;
  28. }
Success #stdin #stdout 1.68s 4568KB
stdin
Standard input is empty
stdout
checking, please wait..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
700020007 is prime.