legacy_future.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #pragma once
  2. #include "fwd.h"
  3. #include "future.h"
  4. #include <util/thread/factory.h>
  5. #include <functional>
  6. namespace NThreading {
  7. template <typename TR, bool IgnoreException>
  8. class TLegacyFuture: public IThreadFactory::IThreadAble, TNonCopyable {
  9. public:
  10. typedef TR(TFunctionSignature)();
  11. using TFunctionObjectType = std::function<TFunctionSignature>;
  12. using TResult = typename TFunctionObjectType::result_type;
  13. private:
  14. TFunctionObjectType Func_;
  15. TPromise<TResult> Result_;
  16. THolder<IThreadFactory::IThread> Thread_;
  17. public:
  18. inline TLegacyFuture(const TFunctionObjectType func, IThreadFactory* pool = SystemThreadFactory())
  19. : Func_(func)
  20. , Result_(NewPromise<TResult>())
  21. , Thread_(pool->Run(this))
  22. {
  23. }
  24. inline ~TLegacyFuture() override {
  25. this->Join();
  26. }
  27. inline TResult Get() {
  28. this->Join();
  29. return Result_.GetValue();
  30. }
  31. private:
  32. inline void Join() {
  33. if (Thread_) {
  34. Thread_->Join();
  35. Thread_.Destroy();
  36. }
  37. }
  38. template <typename Result, bool IgnoreException_>
  39. struct TExecutor {
  40. static void SetPromise(TPromise<Result>& promise, const TFunctionObjectType& func) {
  41. if (IgnoreException_) {
  42. try {
  43. promise.SetValue(func());
  44. } catch (...) {
  45. }
  46. } else {
  47. promise.SetValue(func());
  48. }
  49. }
  50. };
  51. template <bool IgnoreException_>
  52. struct TExecutor<void, IgnoreException_> {
  53. static void SetPromise(TPromise<void>& promise, const TFunctionObjectType& func) {
  54. if (IgnoreException_) {
  55. try {
  56. func();
  57. promise.SetValue();
  58. } catch (...) {
  59. }
  60. } else {
  61. func();
  62. promise.SetValue();
  63. }
  64. }
  65. };
  66. void DoExecute() override {
  67. TExecutor<TResult, IgnoreException>::SetPromise(Result_, Func_);
  68. }
  69. };
  70. }