aboutsummaryrefslogtreecommitdiff
path: root/lib/executor.cc
blob: 52bdf0129a4bbaf1b2522ebf1b5a3ce0c90fa093 (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
/* Copyright (c) 2020 Johannes Stoelp */

#include "executor.h"

#include "arch.h"

namespace nMatcha {
    const void* Executor::getStackPtr() const {
        return mStackPtr;
    }

    void Executor::spawn(std::unique_ptr<Thread> t) {
        mThreads.push_front(std::move(t));
        mThreads.front()->mExecutor = this;
    }

    void Executor::run() {
        // Round robin until all threads finished.
        while (!mThreads.empty()) {
            for (const std::unique_ptr<Thread>& t : mThreads) {
                if (!t->isFinished()) {
                    yield_to(t.get());
                }
            }
            mThreads.remove_if([](const std::unique_ptr<Thread>& t) { return t->isFinished(); });
        }
    }

    void Executor::yield_to(const Thread* t) {
        ::yield(t->mStack.mPtr, &mStackPtr);
    }
}  // namespace nMatcha