Simvik

Message queue

A fixed-size queue that copies whole messages in and out, like an RTOS queue. A medium embedded C problem (RTOS synchronisation), run and graded in the browser.

medium · RTOS synchronisation · rtos · queue · copy-semantics

An RTOS queue copies each message into its own storage, so the sender can reuse its variable straight away. Implement the non-blocking operations:

  • msgq_send(q, item) copies item_size bytes from item to the back of the queue; returns false if the queue is full.
  • msgq_receive(q, item) copies the oldest message into item and removes it; returns false if the queue is empty.

Starter code

bool msgq_send(msgq_t *q, const void *item) {
  return false;
}

bool msgq_receive(msgq_t *q, void *item) {
  return false;
}

Example tests

Two readings in, two out, in order

msgq_t q = { 0 };
q.item_size = sizeof(reading_t);
reading_t a = { 1, -5 }, b = { 2, 300 }, r;
printf("%d%d", msgq_send(&q, &a), msgq_send(&q, &b));
while (msgq_receive(&q, &r)) printf(" %u:%d", r.id, r.value);
printf("\n");

Expected output:

11 1:-5 2:300

A full queue refuses, then accepts once there is room

msgq_t q = { 0 };
q.item_size = sizeof(reading_t);
reading_t x = { 0, 0 }, r;
for (int i = 0; i < 5; i++) { x.id = (uint16_t)i; printf("%d", msgq_send(&q, &x)); }
msgq_receive(&q, &r);
printf(" %u %d\n", r.id, msgq_send(&q, &x));

Expected output:

11110 0 1

Learn it first

More RTOS synchronisation problems

  • Counting semaphore · Implement non-blocking take and give for a semaphore with a maximum count.
  • Wait for event bits · Decide whether a task waiting on an event group may run, and clear the bits it consumed.
  • Priority inheritance · Make a mutex boost its owner's priority while a higher-priority task waits.
  • Recursive mutex · A mutex the owning task may take again, released only when every take is given back.
  • Detect a deadlock · Find a cycle of tasks each waiting for a mutex another one holds.