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:
| Event | Allowed from | Goes to |
|---|---|---|
EV_DISPATCH: the scheduler picks it | ready | running |
EV_PREEMPT: a higher priority task takes over | running | ready |
EV_BLOCK: it waits for a delay, queue or semaphore | running | blocked |
EV_UNBLOCK: what it waited for happened | blocked | ready |
EV_SUSPEND: another task suspends it | ready, running or blocked | suspended |
EV_RESUME: another task resumes it | suspended | ready |
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 runningLearn 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.