Publish and subscribe
Keep a fixed-size list of callbacks and notify them in order. A medium embedded C problem (Function pointers and state machines), run and graded in the browser.
medium · Function pointers and state machines · callbacks · observer
Drivers let several modules react to one event without knowing about them. Implement a registry for at most MAX_CALLBACKS callbacks.
event_subscribe(cb)addscband returnstrue. It returnsfalse, and changes nothing, ifcbisNULL, is already subscribed, or the registry is full.event_publish(event)calls every subscribed callback withevent, in the order they subscribed.
Starter code
static event_cb_t callbacks[MAX_CALLBACKS];
static size_t callback_count;
bool event_subscribe(event_cb_t cb) {
// Reject NULL, duplicates and a full table.
return false;
}
void event_publish(int event) {
// Call each subscriber in subscription order.
}Example tests
Two subscribers
event_subscribe(cb_a);
event_subscribe(cb_b);
event_publish(7);
printf("\n");Expected output:
A7 B7No subscribers
event_publish(1);
printf("done\n");Expected output:
doneLearn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Replace a switch with a table · Select an operation by opcode using an array of function pointers.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- Sort with a comparator · Sort an array into an order defined by a callback.
- State transition function · Implement the transition rules of a motor controller.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- Generic minimum · Find the smallest element of an array of any type using a comparator.
- State handlers · Build a state machine in which each state is a function.
- TV remote: a table of key actions · Look a key code up in a table and call its action with the device's context.