diff options
author | Devtools Arcadia <arcadia-devtools@yandex-team.ru> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /library/cpp/messagebus/async_result.h | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/messagebus/async_result.h')
-rw-r--r-- | library/cpp/messagebus/async_result.h | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/library/cpp/messagebus/async_result.h b/library/cpp/messagebus/async_result.h new file mode 100644 index 0000000000..d24dde284a --- /dev/null +++ b/library/cpp/messagebus/async_result.h @@ -0,0 +1,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_VERIFY(!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); + } + } +}; |