The delay list
Keep delayed tasks sorted by wake time and wake them on the right tick, even when the tick counter wraps. A medium embedded C problem (RTOS fundamentals),…
medium · RTOS fundamentals · rtos · tick · sorted-list · wraparound
When a task calls vTaskDelay(ticks), the kernel puts it in a list sorted by wake time, so the tick interrupt only has to look at the front. Implement:
delay_add(l, task, ticks): delaytaskforticks(at least 1) fromnow. Keep the list sorted soonest first; tasks with the same wake time stay in the order they were added. Returnfalseif the list is full.delay_tick(l, woken): the tick interrupt. Advancenowby one, remove every task whose wake time has come, write them towokenin list order, and return how many.
The tick counter is 32 bits and wraps. A delay that runs across the wrap must still wake on time, and must not be sorted in front of tasks that wake before the wrap.
Starter code
bool delay_add(delay_list_t *l, uint8_t task, uint32_t ticks) {
if (l->n == MAX_DELAYED) return false;
l->item[l->n].task = task;
l->item[l->n].wake = l->now + ticks;
l->n++;
return true;
}
uint8_t delay_tick(delay_list_t *l, uint8_t *woken) {
l->now++;
uint8_t k = 0;
while (k < l->n && l->item[k].wake <= l->now) {
woken[k] = l->item[k].task;
k++;
}
for (uint8_t i = k; i < l->n; i++) l->item[i - k] = l->item[i];
l->n -= k;
return k;
}Example tests
Four delays added out of order
delay_list_t l = {0};
delay_add(&l, 1, 10);
delay_add(&l, 2, 3);
delay_add(&l, 3, 7);
delay_add(&l, 4, 3);
run_ticks(&l, 12);Expected output:
t=3: T2 T4
t=7: T3
t=10: T1A full list refuses another task
delay_list_t l = {0};
int added = 0;
for (uint8_t t = 0; t < 9; t++) added += delay_add(&l, t, 5);
printf("added %d\n", added);
run_ticks(&l, 5);Expected output:
added 8
t=5: T0 T1 T2 T3 T4 T5 T6 T7Learn it first
- RTOS fundamentals · Hard and soft real time, tasks, states, and FreeRTOS versus Zephyr.
More RTOS fundamentals problems
- Task states · Move a task between ready, running, blocked and suspended, and refuse illegal moves.