blob: be8c9c1f95b8192049fee6a7bd11ee0c4139df94 (
plain) (
blame)
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
|
#pragma once
#include <util/generic/maybe.h>
#include <util/generic/noncopyable.h>
#include <util/system/condvar.h>
#include <util/system/mutex.h>
#include <util/system/yassert.h>
#include <functional>
// probably this thing should have been called TFuture
template <typename T>
class TAsyncResult : TNonCopyable {
private:
TMutex Mutex;
TCondVar CondVar;
TMaybe<T> Result;
typedef void TOnResult(const T&);
std::function<TOnResult> OnResult;
public:
void SetResult(const T& result) {
TGuard<TMutex> guard(Mutex);
Y_ABORT_UNLESS(!Result, "cannot set result twice");
Result = result;
CondVar.BroadCast();
if (!!OnResult) {
OnResult(result);
}
}
const T& GetResult() {
TGuard<TMutex> guard(Mutex);
while (!Result) {
CondVar.Wait(Mutex);
}
return *Result;
}
template <typename TFunc>
void AndThen(const TFunc& onResult) {
TGuard<TMutex> guard(Mutex);
if (!!Result) {
onResult(*Result);
} else {
Y_ASSERT(!OnResult);
OnResult = std::function<TOnResult>(onResult);
}
}
};
|