summaryrefslogtreecommitdiff
path: root/future-example.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'future-example.cpp')
-rw-r--r--future-example.cpp26
1 files changed, 26 insertions, 0 deletions
diff --git a/future-example.cpp b/future-example.cpp
new file mode 100644
index 0000000..e5df3a5
--- /dev/null
+++ b/future-example.cpp
@@ -0,0 +1,26 @@
+// async example
+#include <iostream> // std::cout
+#include <future> // std::async, std::future
+
+// a non-optimized way of checking for prime numbers:
+bool 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 ()
+{
+ // call is_prime(313222313) asynchronously:
+ std::future<bool> fut = std::async (is_prime,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;
+}