summaryrefslogtreecommitdiff
path: root/src/egg/core/eggThreadMgr.cpp
blob: e5fcd44a49c3b351b193dbb7d02a87ef7dac2c07 (plain)
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
#include "egg/core/eggThreadMgr.h"

#include "rvl/OS.h"

namespace EGG {

ThreadMgr *ThreadMgr::sInstance; // Never initialized

s32 ThreadMgr::getThreadIndex(OSThread *thread) {
    for (s32 i = 0; i < mThreadCount; i++) {
        if (mThreadList[i].mThread == thread) {
            return i;
        }
    }
    return -1;
}

s32 ThreadMgr::doRegisterThread(OSThread *thread) {
    if (mThreadCount != mMaxThreads) {
        s32 i = mThreadCount;

        mThreadList[i].mThread = thread;
        mThreadList[i]._04 = _EC;
        mThreadList[i]._08 = true;
        mThreadList[i]._09[0] = '\0';
        mThreadList[i]._2C = _F4;

        mThreadCount++;

        if (mSortEnabled) {
            sortByPriority();
        }

        return getThreadIndex(thread);
    }

    return -1;
}

void ThreadMgr::sortByPriority() {
    // Selection sort on thread priority
    for (s32 i = 0; i < mThreadCount - 1; i++) {
        OSPriority minPrio = 31;
        s32 minPrioIndex = -1;

        for (s32 j = i; j < mThreadCount; j++) {
            OSPriority prio = OSGetThreadPriority(mThreadList[j].mThread);
            if (prio <= minPrio) {
                minPrio = prio;
                minPrioIndex = j;
            }
        }

        if (i != minPrioIndex) {
            ThreadInfo temp = mThreadList[i];
            mThreadList[i] = mThreadList[minPrioIndex];
            mThreadList[minPrioIndex] = temp;
        }
    }
}

void ThreadMgr::registerThread(OSThread *thread, UnknownStruct arg) {
    s32 i = getThreadIndex(thread);
    if (i == -1) {
        i = doRegisterThread(thread);
    }

    if (i != -1) {
        mThreadList[i]._04 = arg;
    }
}

} // namespace EGG