forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_exceptions.cpp
More file actions
59 lines (49 loc) · 1.11 KB
/
03_exceptions.cpp
File metadata and controls
59 lines (49 loc) · 1.11 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
#include <chrono>
#include <cstdio>
#include <stdexcept>
#include <thread>
void foo() { printf("Hello from function foo.\n"); }
void hazard() {
printf("Throwing operation\n");
throw std::runtime_error("Runtime Error in hazard() operation");
}
// thread_guard implements RAII for std::thread.
class thread_guard {
std::thread &t;
public:
// no implicit conversions
explicit thread_guard(std::thread &_t) : t(_t) {}
// calls join
~thread_guard() {
if (t.joinable()) {
t.join();
}
}
// non-copiable.
thread_guard(thread_guard const &) = delete;
thread_guard &operator=(thread_guard const &) = delete;
};
void example_try_catch() {
std::thread foo_thread(foo);
// Using try catch solves the issue, but exceptions could still be thrown on
// more complex scenarios where try/catch is forgotten.
try {
hazard();
foo_thread.join();
} catch (...) {
foo_thread.join();
}
}
void example_raii() {
std::thread foo_thread(foo);
thread_guard tg(foo_thread);
try {
hazard();
} catch (...) {
}
}
int main() {
example_try_catch();
example_raii();
return 0;
}