forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_shared_future.cpp
More file actions
65 lines (51 loc) · 1.55 KB
/
08_shared_future.cpp
File metadata and controls
65 lines (51 loc) · 1.55 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
61
62
63
64
65
#include <chrono>
#include <future>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <thread>
// ===================================================================
// EXAMPLE 1: Shared Future.
// - Calling multiple get() results in exception.
// ===================================================================
void print_result1(std::future<int> &fut) {
// Exception when called multiple times!
// std::cout << fut.get() << "\n";
// The problem persists even if checking beforehand, because of race
// condition between valid() and get().
if (fut.valid()) {
std::cout << "this is valid future\n";
std::cout << fut.get() << "\n";
} else {
std::cout << "this is invalid future\n";
}
}
void run_code1() {
std::promise<int> prom;
std::future<int> fut(prom.get_future());
std::thread th1(print_result1, std::ref(fut));
std::thread th2(print_result1, std::ref(fut));
prom.set_value(5);
th1.join();
th2.join();
}
// ===================================================================
// EXAMPLE 2: std::shared_future
// ===================================================================
void print_result2(std::shared_future<int> &fut) {
std::cout << fut.get() << " - valid future \n";
}
void run_code2() {
std::promise<int> prom;
std::shared_future<int> fut(prom.get_future());
std::thread th1(print_result2, std::ref(fut));
std::thread th2(print_result2, std::ref(fut));
prom.set_value(5);
th1.join();
th2.join();
}
int main() {
// run_code1(); // <-- Exception
run_code2();
return 0;
}