Simvik

Counting semaphore

Implement non-blocking take and give for a semaphore with a maximum count. An easy embedded C problem (RTOS synchronisation), run and graded in the browser.

easy · RTOS synchronisation · rtos · semaphore

A counting semaphore holds up to max tokens. Implement the non-blocking versions of its two operations:

  • csem_take takes a token and returns true, or returns false if there are none.
  • csem_give returns a token and returns true, or returns false if the semaphore is already full.

Starter code

bool csem_take(csem_t *s) {
  s->count--;
  return true;
}

bool csem_give(csem_t *s) {
  s->count++;
  return true;
}

Example tests

Give up to the maximum

csem_t s = { 0, 3 };
ops(&s, "gggg");

Expected output:

1110 3

Take until empty

csem_t s = { 2, 3 };
ops(&s, "ttt");

Expected output:

110 0

Learn it first

More RTOS synchronisation problems

  • 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.
  • Message queue · A fixed-size queue that copies whole messages in and out, like an RTOS queue.
  • Detect a deadlock · Find a cycle of tasks each waiting for a mutex another one holds.