Skip to content

Instantly share code, notes, and snippets.

@randhawp
Created October 9, 2019 16:23
Show Gist options
  • Save randhawp/002a6a4371cf8a1b5bbcd9fde533308f to your computer and use it in GitHub Desktop.
Save randhawp/002a6a4371cf8a1b5bbcd9fde533308f to your computer and use it in GitHub Desktop.
// async example
#include <iostream> // std::cout
#include <future> // std::async, std::future
// a non-optimized way of checking for prime numbers:
class X{
public:
X(){};
~X(){};
bool is_prime (int x);
};
bool X::is_prime(int x) {
std::cout << "Calculating. Please, wait...\n";
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
};
int main ()
{
bool taking_photo = true;
int count=0;
X x;
// call is_prime(313222313) asynchronously:
std::future<bool> fut = std::async ( &X::is_prime,&x,313222313);
std::cout << "Checking whether 313222313 is prime.\n";
// ...
bool ret = fut.get(); // waits for is_prime to return
if (ret) std::cout << "It is prime!\n";
else std::cout << "It is not prime.\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment