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/threading/future/legacy_future.h | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/threading/future/legacy_future.h')
-rw-r--r-- | library/cpp/threading/future/legacy_future.h | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/library/cpp/threading/future/legacy_future.h b/library/cpp/threading/future/legacy_future.h new file mode 100644 index 0000000000..6f1eabad73 --- /dev/null +++ b/library/cpp/threading/future/legacy_future.h @@ -0,0 +1,83 @@ +#pragma once + +#include "fwd.h" +#include "future.h" + +#include <util/thread/factory.h> + +#include <functional> + +namespace NThreading { + template <typename TR, bool IgnoreException> + class TLegacyFuture: public IThreadFactory::IThreadAble, TNonCopyable { + public: + typedef TR(TFunctionSignature)(); + using TFunctionObjectType = std::function<TFunctionSignature>; + using TResult = typename TFunctionObjectType::result_type; + + private: + TFunctionObjectType Func_; + TPromise<TResult> Result_; + THolder<IThreadFactory::IThread> Thread_; + + public: + inline TLegacyFuture(const TFunctionObjectType func, IThreadFactory* pool = SystemThreadFactory()) + : Func_(func) + , Result_(NewPromise<TResult>()) + , Thread_(pool->Run(this)) + { + } + + inline ~TLegacyFuture() override { + this->Join(); + } + + inline TResult Get() { + this->Join(); + return Result_.GetValue(); + } + + private: + inline void Join() { + if (Thread_) { + Thread_->Join(); + Thread_.Destroy(); + } + } + + template <typename Result, bool IgnoreException_> + struct TExecutor { + static void SetPromise(TPromise<Result>& promise, const TFunctionObjectType& func) { + if (IgnoreException_) { + try { + promise.SetValue(func()); + } catch (...) { + } + } else { + promise.SetValue(func()); + } + } + }; + + template <bool IgnoreException_> + struct TExecutor<void, IgnoreException_> { + static void SetPromise(TPromise<void>& promise, const TFunctionObjectType& func) { + if (IgnoreException_) { + try { + func(); + promise.SetValue(); + } catch (...) { + } + } else { + func(); + promise.SetValue(); + } + } + }; + + void DoExecute() override { + TExecutor<TResult, IgnoreException>::SetPromise(Result_, Func_); + } + }; + +} |