Simvik

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) adds cb and returns true. It returns false, and changes nothing, if cb is NULL, is already subscribed, or the registry is full.
  • event_publish(event) calls every subscribed callback with event, 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 B7

No subscribers

event_publish(1);
printf("done\n");

Expected output:

done

Learn it first

More Function pointers and state machines problems