summaryrefslogtreecommitdiff
path: root/src/TaskMan.cc
blob: bbaf35cf100a5dddd673ecb61a6c8b2c0025384d (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
#include "TaskMan.h"
#include "Task.h"
#include "Main.h"
#include "Local.h"

static Balau::DefaultTmpl<Balau::TaskMan> defaultTaskMan(50);
static Balau::LocalTmpl<Balau::TaskMan> localTaskMan;

Balau::TaskMan::TaskMan() : stopped(false) {
    coro_create(&returnContext, 0, 0, 0, 0);
    if (!localTaskMan.getGlobal())
        localTaskMan.setGlobal(this);
}

Balau::TaskMan * Balau::TaskMan::getTaskMan() { return localTaskMan.get(); }

Balau::TaskMan::~TaskMan() {
    Assert(localTaskMan.getGlobal() != this);
}

void Balau::TaskMan::mainLoop() {
    // We need at least one round before bailing :)
    do {
        taskList::iterator i;
        Task * t;

        // lock pending
        // Adding tasks that were added, maybe from other threads
        for (i = pendingAdd.begin(); i != pendingAdd.end(); i++) {
            Assert(tasks.find(*i) == tasks.end());
            tasks.insert(*i);
        }
        pendingAdd.clear();
        // unlock pending

        // checking "STARTING" tasks, and running them once
        for (i = tasks.begin(); i != tasks.end(); i++) {
            t = *i;
            if (t->getStatus() == Task::STARTING) {
                t->switchTo();
            }
        }

        // That's probably where we poll for events

        // checking "STOPPED" tasks, and destroying them
        bool didDelete;
        do {
            didDelete = false;
            for (i = tasks.begin(); i != tasks.end(); i++) {
                t = *i;
                if ((t->getStatus() == Task::STOPPED) || (t->getStatus() == Task::FAULTED)) {
                    delete t;
                    tasks.erase(i);
                    didDelete = true;
                    break;
                }
            }
        } while (didDelete);
    } while (!stopped && tasks.size() != 0);
}

void Balau::TaskMan::registerTask(Balau::Task * t) {
    // lock pending
    pendingAdd.insert(t);
    // unlock pending
}