aboutsummaryrefslogtreecommitdiffstats
path: root/util/thread/factory.h
blob: 2330435d11ded2841e6e1a70ca627f6de22c6c55 (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
#pragma once

#include <util/generic/ptr.h>
#include <functional>

class IThreadFactory {
public:
    class IThreadAble {
    public:
        inline IThreadAble() noexcept = default;

        virtual ~IThreadAble() = default;

        inline void Execute() {
            DoExecute();
        }

    private:
        virtual void DoExecute() = 0;
    };

    class IThread {
        friend class IThreadFactory;

    public:
        inline IThread() noexcept = default;

        virtual ~IThread() = default;

        inline void Join() noexcept {
            DoJoin();
        }

    private:
        inline void Run(IThreadAble* func) {
            DoRun(func);
        }

    private:
        // it's actually DoStart
        virtual void DoRun(IThreadAble* func) = 0;
        virtual void DoJoin() noexcept = 0;
    };

    inline IThreadFactory() noexcept = default;

    virtual ~IThreadFactory() = default;

    // XXX: rename to Start
    inline THolder<IThread> Run(IThreadAble* func) { 
        THolder<IThread> ret(DoCreate()); 

        ret->Run(func);

        return ret;
    }

    THolder<IThread> Run(std::function<void()> func); 

private:
    virtual IThread* DoCreate() = 0;
};

IThreadFactory* SystemThreadFactory();
void SetSystemThreadFactory(IThreadFactory* pool);