forked from esp8266/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Schedule.cpp
78 lines (70 loc) · 1.59 KB
/
Schedule.cpp
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
#include "Schedule.h"
struct scheduled_fn_t
{
scheduled_fn_t* mNext;
std::function<void(void)> mFunc;
};
static scheduled_fn_t* sFirst = 0;
static scheduled_fn_t* sLast = 0;
static scheduled_fn_t* sFirstUnused = 0;
static scheduled_fn_t* sLastUnused = 0;
static int sCount = 0;
static scheduled_fn_t* get_fn() {
scheduled_fn_t* result = NULL;
// try to get an item from unused items list
if (sFirstUnused) {
result = sFirstUnused;
sFirstUnused = result->mNext;
if (sFirstUnused == NULL) {
sLastUnused = NULL;
}
}
// if no unused items, and count not too high, allocate a new one
else if (sCount != SCHEDULED_FN_MAX_COUNT) {
result = new scheduled_fn_t;
result->mNext = NULL;
++sCount;
}
return result;
}
static void recycle_fn(scheduled_fn_t* fn)
{
if (!sLastUnused) {
sFirstUnused = fn;
}
else {
sLastUnused->mNext = fn;
}
fn->mNext = NULL;
sLastUnused = fn;
}
bool schedule_function(std::function<void(void)> fn)
{
scheduled_fn_t* item = get_fn();
if (!item) {
return false;
}
item->mFunc = fn;
item->mNext = NULL;
if (!sFirst) {
sFirst = item;
}
else {
sLast->mNext = item;
}
sLast = item;
return true;
}
void run_scheduled_functions()
{
scheduled_fn_t* rFirst = sFirst;
sFirst = NULL;
sLast = NULL;
while (rFirst) {
scheduled_fn_t* item = rFirst;
rFirst = item->mNext;
item->mFunc();
item->mFunc = std::function<void(void)>();
recycle_fn(item);
}
}