aboutsummaryrefslogtreecommitdiff
path: root/lib/thread.h
blob: 330489213d137126650ffec3ea641b643db448b8 (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
/* Copyright (c) 2020 Johannes Stoelp */

#pragma once

#include <functional>
#include <memory>

namespace nMatcha {
    struct Executor;

    struct Thread {
        Thread(const Thread&) = delete;
        Thread& operator=(const Thread&) = delete;
        Thread();
        virtual ~Thread() {}

        virtual void threadFn() = 0;

        bool isFinished() const { return mFinished; }

      protected:
        void yield();

      private:
        static void entry(void* obj);
        void* mStackPtr;
        bool mFinished;

        friend struct Executor;
        const Executor* mExecutor;
    };

    struct Yielder {
        virtual void yield() = 0;
    };

    struct FnThread : public Thread, public Yielder {
        using UserFn = std::function<void(Yielder&)>;
        static std::unique_ptr<Thread> make(UserFn f);

      private:
        virtual void threadFn() override;
        virtual void yield() override;

        UserFn mUserFn;

        enum class CreatorToken {};

      public:
        FnThread(CreatorToken, UserFn f) : mUserFn(f) {}
    };
}  // namespace nMatcha