Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 9 min read
Open in the interactive handbook

76г. Binary heap and priority queue: software timers by deadline on a static array

Firmware almost always has a dozen jobs "in N milliseconds": turn off the backlight, repeat a request, release a relay, check the link. There are not enough hardware timers for all of them, so software ones are set up: a list of deadlines and one system tick that checks whether the nearest one has come. The question is how to store the deadlines so that the nearest one is found at once, while adding and cancelling do not cost a pass over the whole list. The answer is a binary heap in an ordinary static array.

Basis: alg.c with a timer queue, a sorted array for comparison and heapsort, built with gcc 12.2.0 on the computer (stm-sys:1) — there the queue removes the nearest deadline and puts a new one 10000 times, with a tick counter that wraps around during the run, and after each step the heap property is checked. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — sizes and stack frames. Work is measured by the number of comparisons and moves, not cycles.

Terms used in the documentation

Original Meaning
binary heap binary heap: a tree in an array, a parent is not greater than its children
priority queue priority queue: always gives out the smallest element
sift up, sift down sifting up and down: restoring order after an insertion or a removal
min-heap a heap with the smallest element at the root
software timer, deadline software timer, the moment it fires
tick counter wraparound tick counter wraparound: after 0xFFFFFFFF comes 0
heapsort heapsort
decrease-key, cancel changing an element's priority, removing an element from the middle

In plain words. Imagine a pile of jobs where the most urgent one is always on top. For that you do not need to keep the whole pile in order: it is enough that every job is more urgent than the two lying "under it". A new job is put at the bottom and raised while it is more urgent than the one above it; the one taken from the top is replaced by the last one, which is lowered. Each time it is a few steps, not a search through the whole pile.


76г.1 What a timer queue needs

Three operations and one restriction:

Operation When How often
take the nearest deadline in every tick of the system timer 1000 times a second with a 1 ms tick
start a timer from tasks and handlers on every event
cancel a timer the reply came before the timeout expired almost as often as starting
restriction: no heap allocator no malloc in an interrupt, fragmentation (11, 25) always

The most frequent action is looking at the nearest deadline; it must be known at once, without a search. Hence two candidates: a sorted array (the nearest is at the edge) and a heap (the nearest is at the root). An unsorted array is out: finding the minimum is a pass over all timers in every tick.


76г.2 A heap in an array

A heap is a binary tree in which every parent is not later than its children. There is no order between siblings, and that is the main point: maintaining a partial order is much cheaper than a full one. No pointers are needed — the tree is laid out in the array level by level, and the links are computed from the index:

Who Index in the array
the root — the nearest deadline 0
children of element i 2i + 1 and 2i + 2
parent of element i (i − 1) / 2, integer division

On the left — a tree of seven circles with deadlines 10 at the root, 20 and 30 on the second level, 50, 40, 70 and 60 on the third, each with its index in the array; on the right — the same array h in memory: 10, 20, 30, 50, 40, 70, 60 with indices from 0 to 6; captions: the deadlines were added in the order 50, 20, 70, 10, 40, 30, 60, every parent is not later than its children, the path from a leaf to the root is log2 n steps

The height of a heap of n elements is about log₂ n, so any operation passes no more than log₂ n levels: for 32 timers — 5.

typedef struct {
    uint32_t due;  /* срок в тиках */
    uint8_t id;    /* номер таймера */
} tq_item_t;
typedef struct {
    tq_item_t h[TQ_CAP]; /* h[0] — ближайший срок */
    uint8_t pos[TQ_CAP]; /* где в пирамиде лежит таймер id; 0xFF — не запущен */
    uint8_t n;
} tq_t;

The pos array is a reverse table: where the timer with a given number lies now. Without it, cancelling a timer requires a search through the whole heap (76г.5).


76г.3 Adding and removing the nearest

Adding: the new element goes to the end and rises while it is earlier than its parent. The parent moves down to its place — there are no swaps, only moves, as in insertion from 76б:

static void sift_up(tq_t *q, unsigned i)
{
    tq_item_t it = q->h[i];
    while (i > 0) {
        unsigned parent = (i - 1) / 2;
        if (!due_before(it.due, q->h[parent].due))
            break;
        tq_put(q, i, q->h[parent]);
        i = parent;
    }
    tq_put(q, i, it);
}

Removing the nearest: the root leaves, the last element is put in its place and lowered — each time towards the earlier of the two children:

unsigned c = 2 * i + 1;
if (c >= q->n)
    break;
if (c + 1 < q->n && due_before(q->h[c + 1].due, q->h[c].due))
    c++;
if (!due_before(q->h[c].due, it.due))
    break;
tq_put(q, i, q->h[c]);
i = c;

tq_put stores the element and at the same time updates pos — so the reverse table is always correct.


76г.4 Deadlines and tick counter wraparound

A 32-bit millisecond counter wraps around after 49.7 days — a device that runs longer will one day see that "now" is less than "the deadline set a second ago". So deadlines are compared not with an ordinary < but by the sign of the difference:

static inline bool due_before(uint32_t a, uint32_t b)
{
    CMP_HOOK();
    return (int32_t)(a - b) < 0;
}

The deadline 0xFFFFFFF0 — 32 ticks before the wrap — must be earlier than the deadline 0x10. The run: due_before(0xFFFFFFF0, 0x10) gave true, while the ordinary comparison 0xFFFFFFF0 < 0x10 gave false. The rule works as long as all deadlines lie closer than half the circle — 2³¹ ticks, 24.9 days with a 1 ms tick. The whole run of 10000 steps starts 4096 ticks before the wrap and passes through it; the deadlines were removed strictly in order.

CMP_HOOK is empty in firmware, on the computer it counts comparisons.


76г.5 Cancelling a timer

A timeout timer is almost always cancelled: the reply came in time. pos[id] helps to find it by number, and then comes the same trick as when removing the root: the last element is put in its place and sifted — up or down, depending on the deadline:

tq_item_t last = q->h[q->n];
tq_put(q, i, last);
sift_up(q, i);
sift_down(q, q->pos[last.id]);

The run: in a queue of 20 timers, timer 7 was cancelled (successfully), then the same one again (refused — no longer running) and timer 0; 18 remained, the heap property and the pos table are correct. Then tq_expire with the current time 1050 removed 10 expired timers — all in deadline order.


76г.6 Processing in the tick

In the tick all expired deadlines are removed, but no more than fit in the output array — the handler time is bounded:

while (q->n && k < max && !due_before(now, q->h[0].due)) {
    fired[k++] = q->h[0].id;
    q->pos[q->h[0].id] = 0xFF;
    q->n--;
    if (q->n) {
        q->h[0] = q->h[q->n];
        sift_down(q, 0);
    }
}

The timer handlers themselves are not called in the tick — their numbers are given to a task or flags, and the heavy work is done outside the interrupt. If the queue is touched by both tasks and the interrupt, tq_start and tq_cancel are executed with the tick interrupt disabled or from a single owner task (7).


76г.7 Against a sorted array

A sorted array keeps the deadlines in descending order, the nearest at the end: removal costs one operation, and insertion shifts everything later than the new deadline. The run: n timers are always in the queue, 10000 times the nearest is removed and a new one with a random deadline is put. Work per step is comparisons plus moves:

Timers heap: average heap: worst step array: average array: worst step
4 8 10 5 6
8 11 15 10 14
16 14 20 21 30
32 17 25 42 62

Up to 8 timers the sorted array is no worse, and at 4 it is even cheaper: its insertion is a simple loop, and at small n there is almost nothing to shift. From 16 timers on the heap wins, and the gap grows: the heap's work grows as log n, the array's as n. At 32 timers the array's worst step is 62 operations, the heap's 25.

Code: the heap (sift_up, sift_down, tq_start, tq_cancel, tq_expire) is 504 bytes on M4, the sorted array (tl_start, tl_pop) is 128 bytes. In FreeRTOS the lists of delayed tasks and timers are sorted lists with O(n) insertion, and for a typical dozen elements this is the right choice. A heap is needed when there are dozens of timers and the worst case in the tick matters.


76г.8 Heapsort

A heap gives an in-place sort: build a heap from the array, then n times move the root to the end and sift the rest. The worst case is n log n, no memory beyond the array, no recursion. That is why it is taken as the fallback in quicksort from 76б when the depth limit runs out.

void sort_heap(int16_t *a, unsigned n)
{
    for (unsigned i = n / 2; i-- > 0;)
        hs_down(a, i, n);
    for (unsigned end = n; end-- > 1;) {
        int16_t t = a[0];
        a[0] = a[end];
        a[end] = t;
        hs_down(a, 0, end);
    }
}

On 256 elements — random, sorted and reversed — from 3106 to 3452 comparisons: more than quicksort on random data (2385 in 76б), but the spread is only 11 %. The code is 58 bytes of sort_heap and 108 bytes of hs_down on M4. It is never stable.


76г.9 Pitfalls

Timers stopped firing after 49 days. The deadlines were compared with an ordinary <, and after the counter wrapped, a new deadline turned out "less" than the current time. Compare by the sign of the difference, (int32_t)(a - b) < 0.

A timer fired although it had been cancelled. The cancellation searched for the timer by iteration and did not find it, because it had already moved during sifting. A reverse table pos[], updated on every move.

After a cancellation the heap "broke". The last element was put in the place of the cancelled one and only lowered. It may turn out earlier than its new parent — it must also be sifted up.

The tick lasts unpredictably long. All expired timers are removed and processed right in the interrupt. Limit the number removed per tick and give the processing to a task.

A deadline further than half the circle. A 30-day timer with a 1 ms tick goes beyond 2³¹ ticks, and the comparison by the sign of the difference flips. Count long intervals in seconds with a separate counter.


76г.10 Summary

Next: section 76д "A hash table without malloc: open addressing, tombstones, FNV-1a and a console command table" — how to find a key in one or two probes in a static array and why deleting from such a table is harder than inserting.

Open in the interactive handbook