Created
October 9, 2019 16:23
-
-
Save randhawp/002a6a4371cf8a1b5bbcd9fde533308f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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