-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path110 Promises and Exceptions.cpp
More file actions
60 lines (49 loc) · 1.01 KB
/
Copy path110 Promises and Exceptions.cpp
File metadata and controls
60 lines (49 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <cmath>
#include <iomanip>
#include <thread>
#include <future>
#include <exception>
using namespace std;
double calculate_pi(int terms)
{
double sum = 0.0;
if (terms < 1)
{
throw runtime_error("Terms cannot be less than 1");
}
for (int i = 0; i < terms; i++)
{
int sign = pow(-1, i);
double term = 1.0 / (i * 2 + 1);
sum += sign * term;
}
return sum * 4;
}
int main()
{
promise<double> promise;
auto do_calculation = [&](int terms) {
try
{
auto result = calculate_pi(terms);
promise.set_value(result);
}
catch (...)
{
promise.set_exception(current_exception());
}
};
thread t1(do_calculation, 1E6);
future<double> future = promise.get_future();
try
{
cout << setprecision(15) << future.get() << endl;
}
catch (const exception &e)
{
cout << e.what() << endl;
}
t1.join();
return 0;
}