Replace sorted_list/vector with callback_list doubly-linked list for timers and frame callbacks

This commit is contained in:
Ian Gulliver
2026-04-11 14:26:53 +09:00
parent aa349e1a36
commit fec0a0f765
5 changed files with 187 additions and 122 deletions

View File

@@ -1,26 +1,25 @@
#pragma once
#include <functional>
#include "pico/time.h"
#include "sorted_list.h"
#include "callback_list.h"
struct timer_entry {
absolute_time_t when;
std::function<void()> fn;
};
inline bool operator<(const timer_entry& a, const timer_entry& b) {
return absolute_time_diff_us(b.when, a.when) < 0;
}
using timer_handle = sorted_list<timer_entry, 16>::node*;
using timer_handle = callback_list<timer_entry, 16>::node*;
struct timer_queue {
sorted_list<timer_entry, 16> queue;
callback_list<timer_entry, 16> list;
alarm_id_t alarm = -1;
volatile bool irq_pending = false;
timer_handle schedule(absolute_time_t when, std::function<void()> fn) {
auto* n = queue.insert({when, std::move(fn)});
auto* n = list.insert_sorted({when, std::move(fn)},
[](const timer_entry& a, const timer_entry& b) {
return absolute_time_diff_us(b.when, a.when) < 0;
});
arm();
return n;
}
@@ -30,25 +29,25 @@ struct timer_queue {
}
bool cancel(timer_handle h) {
bool removed = queue.remove(h);
if (removed) arm();
return removed;
if (!h || !h->active) return false;
list.remove(h);
arm();
return true;
}
void run() {
if (!irq_pending) return;
irq_pending = false;
while (!queue.empty()) {
auto& front = queue.front();
if (absolute_time_diff_us(get_absolute_time(), front.when) > 0) break;
auto fn = std::move(front.fn);
queue.pop_front();
while (auto* n = list.front()) {
if (absolute_time_diff_us(get_absolute_time(), n->value().when) > 0) break;
auto fn = std::move(n->value().fn);
list.remove(n);
fn();
}
arm();
}
bool empty() const { return queue.empty(); }
bool empty() const { return list.empty(); }
private:
static int64_t alarm_cb(alarm_id_t, void* user_data) {
@@ -59,7 +58,7 @@ private:
void arm() {
if (alarm >= 0) cancel_alarm(alarm);
alarm = -1;
if (!queue.empty())
alarm = add_alarm_at(queue.front().when, alarm_cb, this, false);
if (auto* n = list.front())
alarm = add_alarm_at(n->value().when, alarm_cb, this, false);
}
};