//g++ -std=c++11 -pthread -g std_future.cpp -o main
// async example
#include <iostream> // std::cout
#include <future> // std::async, std::future
// a non-optimized way of checking for prime numbers:
bool is_prime (long int x) {
std::cout << "Calculating " << x << ". Please, wait...\n";
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
long int x3=2147483647;
long int x2=623222313;
long int x1=444444443;
// call is_prime(313222313) asynchronously:
std::cout << "Start Checking whether " << x1 << " is prime.\n";
std::future<bool> fut1 = std::async (std::launch::async, is_prime,x1);
std::cout << "Start Checking whether " << x2 << " is prime.\n";
std::future<bool> fut2 = std::async (std::launch::async, is_prime,x2);
std::cout << "Start Checking whether " << x3 << " is prime.\n";
std::future<bool> fut3 = std::async (std::launch::async, is_prime,x3);
std::cout << x1 << (fut1.get() ? " is prime\n" : " is not prime\n");
std::cout << x2 << (fut2.get() ? " is prime\n" : " is not prime\n");
std::cout << x3 << (fut3.get() ? " is prime\n" : " is not prime\n");
return 0;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。