0%

How to pass exception between threads in C++11

長知識了,直接看Code比較快

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
int calc(std::exception_ptr& eptr)
{
try {
std::string s;
s.at(0); // throw out of range exception
} catch (...) {
eptr = std::current_exception();
}
return 0;
}
int main()
{
std::exception_ptr eptr;
auto f = std::async(std::launch::async, std::bind(calc, std::ref(eptr)));
try {
int i = f.get();
if (eptr) {
std::rethrow_exception(eptr);
}
std::cout << i << std::endl;
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}ion_ptr eptr;
auto f = std::async(std::launch::async, std::bind(calc, std::ref(eptr)));
try {
int i = f.get();
if (eptr) {
std::rethrow_exception(eptr);
}
std::cout << i << std::endl;
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}

如果要在Thread傳輸exception的食,記得紀錄一個exception_ptr,當exception發生食,用current_exception()捕捉在當今thread發生的excetipn。然後其他Thread發現這個eptr存在的話,透過rethrow_exception處理這個exception。
不過這樣作一點都不直覺啊

Better Solution

搭配同時加入C++11的thread和future,可以寫出更加優雅的Code,promise不僅解決了exception的問題,同時也提供了Thread return value的問題>

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
void calc(std::promise<int> && p)
{
try {
std::string s;
s.at(0); // throw out of range exception
p.set_value(0);
} catch (...) {
p.set_exception(std::current_exception());
}
}
int main()
{
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread thd(calc, std::move(p));
try {
int i = f.get();
std::cout << i << std::endl;
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
thd.join();
return 0;
}

‵``