Simvik

Task states

Move a task between ready, running, blocked and suspended, and refuse illegal moves. An easy embedded C problem (RTOS fundamentals), run and graded in the…

easy · RTOS fundamentals · rtos · task-states · state-machine

An RTOS keeps every task in one of four states. Implement task_event(s, e), which applies an event to the state in *s and returns true, or returns false and leaves the state unchanged if the move is not allowed:

EventAllowed fromGoes to
EV_DISPATCH: the scheduler picks itreadyrunning
EV_PREEMPT: a higher priority task takes overrunningready
EV_BLOCK: it waits for a delay, queue or semaphorerunningblocked
EV_UNBLOCK: what it waited for happenedblockedready
EV_SUSPEND: another task suspends itready, running or blockedsuspended
EV_RESUME: another task resumes itsuspendedready

Starter code

bool task_event(task_state_t *s, task_event_t e) {
  switch (e) {
  case EV_DISPATCH: *s = ST_RUNNING; break;
  case EV_PREEMPT:  *s = ST_READY; break;
  case EV_BLOCK:    *s = ST_BLOCKED; break;
  case EV_UNBLOCK:  *s = ST_READY; break;
  case EV_SUSPEND:  *s = ST_SUSPENDED; break;
  case EV_RESUME:   *s = ST_READY; break;
  }
  return true;
}

Example tests

Run, wait, wake, then an illegal resume

run(ST_READY, "dbur");

Expected output:

running blocked ready ready!

Suspended while running

run(ST_READY, "dsrd");

Expected output:

running suspended ready running

Learn it first

  • RTOS fundamentals · Hard and soft real time, tasks, states, and FreeRTOS versus Zephyr.

More RTOS fundamentals problems

  • The delay list · Keep delayed tasks sorted by wake time and wake them on the right tick, even when the tick counter wraps.