-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.c
102 lines (89 loc) · 1.61 KB
/
scheduler.c
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <limits.h>
#include "scheduler.h"
Task _tasks[MAX_TASKS];
void InitScheduler() {
for (TaskId i=0; i < MAX_TASKS; ++i)
{
_tasks[i].state = EMPTY;
}
}
inline static TaskId _find(TaskState st) {
for (TaskId i = 0; i < MAX_TASKS; ++i)
{
if (_tasks[i].state==st) {
return i;
}
}
return NONE;
}
inline static Time _soonest_task() {
Time minTime = INT_MAX;
for (TaskId i = 0; i < MAX_TASKS; ++i)
{
Task* t = &_tasks[i];
if (t->state==WAITING) {
if (minTime>t->delay) {
minTime = t->delay;
}
}
}
return minTime;
}
inline static void _updateTasks(Time elapsed) {
for (TaskId i = 0; i < MAX_TASKS; ++i)
{
Task* t = &_tasks[i];
if (t->state==WAITING) {
if (t->delay <= elapsed) {
// Call the func
t->func(t->param);
// Reschedule
if (t->period) {
t->state = WAITING;
t->delay = t->period;
} else {
t->state = EMPTY;
}
}
else
{
t->delay -= elapsed;
}
}
}
}
TaskId AddSchedulerTask(
TaskFunction func,
Time period,
Time delay,
void* param,
Time elapsedTime)
{
// Update the tasks in the queue
// Fire the events if necessary
if (elapsedTime) {
_updateTasks(elapsedTime);
}
// Insert the new task to the queue
TaskId i = _find(EMPTY);
if (i == NONE) {
return 0;
}
Task* t = &_tasks[i];
t->func = func;
t->period = period;
t->delay = delay;
t->param = param;
t->state = WAITING;
return i;
}
Time SchedulerTick(Time elapsed) {
_updateTasks(elapsed);
return _soonest_task();
}
Time GetNextSchedulerTime() {
return _soonest_task();
}
void RemoveSchedulerTask(TaskId taskId) {
_tasks[taskId].state = EMPTY;
}