Simvik

Interrupt-safe byte queue

A single-producer, single-consumer queue with 8-bit free-running indices that must survive wrapping. A hard embedded C problem (ISR-to-task patterns), run…

hard · ISR-to-task patterns · isr · lock-free · ring-buffer · wraparound

A UART receive interrupt pushes bytes and a task reads them in batches. There is no shared count field and no lock: the ISR is the only writer of head, the task the only writer of tail. Both are free-running: they only ever increase, wrapping from 255 to 0, and the slot index is the counter modulo Q_SIZE. The number of bytes waiting is always head - tail in 8-bit arithmetic.

  • q_isr_push(q, b): if the queue holds Q_SIZE bytes, count the byte in dropped; otherwise store it and advance head.
  • q_task_read(q, out, max): copy up to max waiting bytes, oldest first, into out, advance tail and return how many were copied.

The starter works until the counters wrap past 255. Make it correct forever.

Starter code

void q_isr_push(spsc_t *q, uint8_t b) {
  if (q->head - q->tail >= Q_SIZE) {
    q->dropped++;
    return;
  }
  q->buf[q->head % Q_SIZE] = b;
  q->head++;
}

uint8_t q_task_read(spsc_t *q, uint8_t *out, uint8_t max) {
  uint8_t n = 0;
  while (q->tail < q->head && n < max) {
    out[n++] = q->buf[q->tail % Q_SIZE];
    q->tail++;
  }
  return n;
}

Example tests

Read a short message in batches of two

spsc_t q = {0};
push_str(&q, "hello");
read_all(&q, 2);

Expected output:

read: [he] [ll] [o] dropped 0

Keep going past 256 bytes

spsc_t q = {0};
uint8_t out[Q_SIZE];
for (int round = 0; round < 40; round++) {
  push_str(&q, "abcdefg");
  q_task_read(&q, out, Q_SIZE);
}
push_str(&q, "xyz");
read_all(&q, 8);

Expected output:

read: [xyz] dropped 0

Learn it first

More ISR-to-task patterns problems