Deferred interrupt lines
Record interrupts in a pending mask and let the task handle them in priority order. A medium embedded C problem (ISR-to-task patterns), run and graded in the…
medium · ISR-to-task patterns · isr · deferred-work · bits
Interrupt handlers should be short, so each ISR only records that its line fired and the task does the work later. Implement both halves:
irq_raise(s, line)is called from the ISR forline(0 to 31). It marks the line pending. If the line is already pending, the earlier event has not been handled yet and this one is lost: count it inlost[line]instead.irq_next(s)is called by the task. It returns the pending line with the lowest number (the highest priority) and clears it, or returns-1if nothing is pending.
Starter code
void irq_raise(irq_state_t *s, unsigned line) {
s->pending |= 1u << line;
}
int irq_next(irq_state_t *s) {
return -1;
}Example tests
Three lines, handled lowest first
irq_state_t s = {0};
irq_raise(&s, 5);
irq_raise(&s, 1);
irq_raise(&s, 3);
drain(&s);
show_lost(&s);Expected output:
handled: 1 3 5
lost: noneA line that fires again before it is handled
irq_state_t s = {0};
irq_raise(&s, 4);
irq_raise(&s, 4);
drain(&s);
show_lost(&s);Expected output:
handled: 4
lost: 4:1Learn it first
- ISR-to-task patterns · Deferring work out of interrupts with semaphores, queues and notifications.
More ISR-to-task patterns problems
- Fix: fast presses are lost · A button counter misses presses when they come faster than the main loop.
- Interrupt-safe byte queue · A single-producer, single-consumer queue with 8-bit free-running indices that must survive wrapping.