aboutsummaryrefslogtreecommitdiffstats
path: root/util/thread/factory.cpp
blob: 48e898f32dcee56febea62e768d83645a6cbe3a7 (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
84
85
86
87
88
89
90
91
92
93
#include "factory.h"

#include <util/system/thread.h>
#include <util/generic/singleton.h>

using IThread = IThreadFactory::IThread;

namespace {
    class TSystemThreadFactory: public IThreadFactory {
    public:
        class TPoolThread: public IThread {
        public:
            ~TPoolThread() override {
                if (Thr_) {
                    Thr_->Detach();
                }
            }

            void DoRun(IThreadAble* func) override {
                Thr_.Reset(new TThread(ThreadProc, func));

                Thr_->Start();
            }

            void DoJoin() noexcept override {
                if (!Thr_) {
                    return;
                }

                Thr_->Join();
                Thr_.Destroy();
            }

        private:
            static void* ThreadProc(void* func) {
                ((IThreadAble*)(func))->Execute();

                return nullptr;
            }

        private:
            THolder<TThread> Thr_;
        };

        inline TSystemThreadFactory() noexcept {
        }

        IThread* DoCreate() override {
            return new TPoolThread;
        }
    };

    class TThreadFactoryFuncObj: public IThreadFactory::IThreadAble {
    public:
        TThreadFactoryFuncObj(const std::function<void()>& func)
            : Func(func)
        {
        }
        void DoExecute() override {
            THolder<TThreadFactoryFuncObj> self(this);
            Func();
        }

    private:
        std::function<void()> Func;
    };
}

THolder<IThread> IThreadFactory::Run(std::function<void()> func) {
    THolder<IThread> ret(DoCreate());

    ret->Run(new ::TThreadFactoryFuncObj(func));

    return ret;
}

static IThreadFactory* SystemThreadPoolImpl() {
    return Singleton<TSystemThreadFactory>();
}

static IThreadFactory* systemPool = nullptr;

IThreadFactory* SystemThreadFactory() {
    if (systemPool) {
        return systemPool;
    }

    return SystemThreadPoolImpl();
}

void SetSystemThreadFactory(IThreadFactory* pool) {
    systemPool = pool;
}