-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathasync.hxx
72 lines (60 loc) · 1.84 KB
/
async.hxx
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
66
67
68
69
70
71
72
#ifndef _ASYNC_HXX_
#define _ASYNC_HXX_
namespace cornerstone {
template<typename T, typename TE = ptr<std::exception>>
class async_result {
public:
typedef std::function<void(T&, TE&)> handler_type;
async_result() : err_(), has_result_(false), lock_(), cv_() {}
explicit async_result(T& result)
: result_(result), err_(), has_result_(true), lock_(), cv_() {}
explicit async_result(handler_type& handler)
: err_(), has_result_(true), handler_(handler), lock_(), cv_() {}
~async_result() {}
__nocopy__(async_result)
public:
void when_ready(handler_type& handler) {
std::lock_guard<std::mutex> guard(lock_);
if (has_result_) {
handler(result_, err_);
}
else {
handler_ = handler;
}
}
void set_result(T& result, TE& err) {
{
std::lock_guard<std::mutex> guard(lock_);
result_ = result;
err_ = err;
has_result_ = true;
if (handler_) {
handler_(result, err);
}
}
cv_.notify_all();
}
T& get() {
std::unique_lock<std::mutex> lock(lock_);
if (has_result_) {
if (err_ == nullptr) {
return result_;
}
throw err_;
}
cv_.wait(lock);
if (err_ == nullptr) {
return result_;
}
throw err_;
}
private:
T result_;
TE err_;
bool has_result_;
handler_type handler_;
std::mutex lock_;
std::condition_variable cv_;
};
}
#endif //_ASYNC_HXX_