Defer events until the machine is ready
Hold START requests that arrive while busy, and replay them when idle. A medium embedded C problem (Event-driven state machines), run and graded in the browser.
medium · Event-driven state machines · fsm · events · queues
A machine runs jobs one at a time. Events arrive at any moment, and a state machine must never drop one it will need later. Write dispatch(m, ev):
- IDLE:
EV_STARTcallslog_start(m)and moves to BUSY. Other events are ignored. - BUSY:
EV_STARTcannot run now: defer it (count it indeferred).EV_DONEreturns to IDLE and then, if any START is deferred, takes one and handles it immediately (so the machine starts the next job and is BUSY again).EV_CANCELreturns to IDLE and discards all deferred STARTs.
Starter code
void dispatch(machine_t *m, event_t ev) {
if (m->state == IDLE && ev == EV_START) { log_start(m); m->state = BUSY; }
else if (m->state == BUSY && (ev == EV_DONE || ev == EV_CANCEL)) m->state = IDLE;
}Example tests
One job
machine_t m = {0};
event_t e[] = { EV_START, EV_DONE };
feed(&m, e, 2);Expected output:
start job 1
IDLE, 0 deferred, 1 jobsRequests while busy are not lost
machine_t m = {0};
event_t e[] = { EV_START, EV_START, EV_START, EV_DONE, EV_DONE };
feed(&m, e, 5);Expected output:
start job 1
start job 2
start job 3
BUSY, 0 deferred, 3 jobsLearn it first
- Event-driven state machines · From polling to events, queues and run-to-completion.
More Event-driven state machines problems
- Pump controller with timers · An event-driven state machine with a timeout, where a timeout already queued must not act after its timer was cancelled.
- Train doors: safe in any order of events · A door controller that reverses on an obstacle and never opens while the train moves.