aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/threading/future/legacy_future.h
blob: c699aadf5cd67461d7952435f25445df05364935 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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_); 
        }
    };

}