forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_promise_exception.cpp
More file actions
45 lines (39 loc) · 1.01 KB
/
07_promise_exception.cpp
File metadata and controls
45 lines (39 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <cmath>
#include <future>
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <thread>
void throw_exception() {
throw std::invalid_argument("input cannot be negative");
}
void calculate_squre_root(std::promise<int> &prom) {
int x = 1;
std::cout << "Please, enter an integer value: ";
try {
std::cin >> x;
if (x < 0) {
throw_exception();
}
prom.set_value(std::sqrt(x));
} catch (std::exception &) {
// Propagate exception!
prom.set_exception(std::current_exception());
}
}
void print_result(std::future<int> &fut) {
try {
int x = fut.get();
std::cout << "value: " << x << '\n';
} catch (std::exception &e) {
std::cout << "[exception caught: " << e.what() << "]\n";
}
}
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread printing_thread(print_result, std::ref(fut));
std::thread calculation_thread(calculate_squre_root, std::ref(prom));
printing_thread.join();
calculation_thread.join();
}