OOP and design patterns
Design is a decision
Functional proramming, imperative programming, object-oriented programming… In university courses the focus was on learning codeing principles like a linguist views languages. There, the focus is often correctionistic, about syntax, lexical integrity, correct sematics, and, how expressive a given language is. Constructing an expressive langauge is an art of it’s own, do not concider me an expert on the subject, but still, there are patterns we follow as developers when designing software that we typically orient towards.
Let’s talk about OOP for a moment.
The thing is that the patterns OOP puts out explicitly, say for example polymorphism and inheritance, are embedded to language itself, say Python, Java or C++. A programmer with root in an OOP language, jumping to for example C, quickly realizes that the syntax of the language doesn’t imply the same kind of structure. The programmer becomes both dazzled and frightened by the amount of freedom given by a imperative, multi-paradigm language that C is.
In C it is now the responsibility of the programmer to establish the conventions and patterns used in the software design. Say goodbye intersystem modularity (and hello to unbounded performance)!
What I want to focus on in this post is the impotrance of enforcing certain software design patterns. Emergent behaviour comes from the design interactions, which are at worst conflicting. The explicit patterns of higher-level OOP programming languages can be implemented in C, by the developer. In the following sections we’ll briefly go through 8 different design patterns, and look at basic software components like loggers and sinks. The patters are:
- Object pattern
- Opaque pattern
- Singleton pattern
- Factory pattern
- Callback pattern
- Inheritance pattern
- Bridge pattern
- Return value pattern
Design patterns, in C
Object pattern
In object pattern all function calls and variables are encapsulated inside a single object. This ensures a code section is only modified through an abtract interface. The object design makes it possible to create several instances of an object, given a “object blueprint”. Take for example a global logger object versus a subsystem specific logger.
One way to implement this in C is:
my_logger.h
#ifndef MY_LOGGER_H
#define MY_LOGGER_H
#include <stddef.h>
#include <stdint.h>
#define LOGGER_BUF_SIZE 64u
enum logger_level {
LOGGER_ERROR = 0,
LOGGER_WARN,
LOGGER_INFO,
LOGGER_DEBUG,
};
/* The "blueprint". Every instance carries its own state. */
struct logger {
const char *prefix;
enum logger_level level;
uint32_t written;
uint32_t dropped;
char buf[LOGGER_BUF_SIZE];
};
int32_t logger_init(struct logger *self, const char *prefix, enum logger_level level);
int32_t logger_set_level(struct logger *self, enum logger_level level);
int32_t logger_log(struct logger *self, enum logger_level level, const char *msg);
const char *logger_last(const struct logger *self);
#endif /* LOGGER_H */
The implementation:
#include "logger.h"
#include <stdio.h>
#include <string.h>
static const char *const level_tag[] = { "E", "W", "I", "D" };
int32_t logger_init(struct logger *self, const char *prefix, enum logger_level level)
{
if (self == NULL || prefix == NULL) {
return -1;
}
memset(self, 0, sizeof(*self));
self->prefix = prefix;
self->level = level;
return 0;
}
int32_t logger_set_level(struct logger *self, enum logger_level level)
{
if (self == NULL || level > LOGGER_DEBUG) {
return -1;
}
self->level = level;
return 0;
}
int32_t logger_log(struct logger *self, enum logger_level level, const char *msg)
{
if (self == NULL || msg == NULL || level > LOGGER_DEBUG) {
return -1;
}
if (level > self->level) {
self->dropped++;
return 0;
}
int n = snprintf(self->buf, sizeof(self->buf), "[%s] %s: %s",
level_tag[level], self->prefix, msg);
if (n < 0) {
return -1;
}
self->written++;
return n;
}
const char *logger_last(const struct logger *self)
{
return (self != NULL) ? self->buf : "";
}
#include <stdio.h>
#include "logger.h"
int main(void)
{
struct logger sys_log;
struct logger motor_log;
logger_init(&sys_log, "sys", LOGGER_INFO);
logger_init(&motor_log, "motor", LOGGER_DEBUG);
logger_log(&sys_log, LOGGER_INFO, "boot complete");
logger_log(&sys_log, LOGGER_DEBUG, "this one is dropped");
logger_log(&motor_log, LOGGER_DEBUG, "pwm duty 42 %");
printf("%s\n", logger_last(&sys_log));
printf("%s\n", logger_last(&motor_log));
printf("sys: written=%u dropped=%u\n", sys_log.written, sys_log.dropped);
return 0;
}
The object functions (kinda like methods) act on a given data structure with pointer reference *self, which is a literally a struct base pointer. In object pattern, the a function acting on an object struct shouldn’t access global variables nor should call other functions that access global variables. So, encapsulation. Respect the pattern, and all function effect stay contained in object structs.
As an example in ARM’s CMSIS standard, different peripheral drivers are implemented as structs.
Opaque pattern
As the name suggests, in the opaque pattern the definition of the data structure is hidden from the user. Only a forward declaration struct my_obj; is visible in the header, and the client works through a pointer to it. This comes with several benefits:
- Compiler-enforced encapsulation.
my_obj->var = 0no longer compiles, so the module’s invariants can only be broken by the module itself. - Binary compatibility.
libchands outFILE *. Because clients never see the size or the layout ofFILE *itself, the library can change without the clients recompiling. - Swappable implementations. A client can link to different implementations. This implies test mocks, POSIX ports, register abstaction layers.
- Controlled lifetime. The client cannot define an instance of a type whose size is uknown:
struct my_opaque_obj. Instead an initialization function likemy_opaque_obj_create()is enforced. Think C++ and RAII.
TSince every access goes through the module’s functions, there is a single place to add bounds checks, tracing or a lock. Where the object is allocated is hidden too, which is sometimes good and sometimes bad: the client cannot put it on the stack, in DMA-capable RAM, or know its footprint.
Let’s see the logger using opaque pattern:
my_opaque_logger.h
#ifndef LOGGER_H
#define LOGGER_H
#include <stdint.h>
enum logger_level {
LOGGER_ERROR = 0,
LOGGER_WARN,
LOGGER_INFO,
LOGGER_DEBUG,
};
/* Incomplete type: callers only ever hold a pointer to it. */
struct logger;
struct logger *logger_create(const char *prefix, enum logger_level level);
void logger_destroy(struct logger *self);
int32_t logger_set_level(struct logger *self, enum logger_level level);
int32_t logger_log(struct logger *self, enum logger_level level, const char *msg);
const char *logger_last(const struct logger *self);
uint32_t logger_dropped(const struct logger *self);
#endif /* LOGGER_H */
And the implementation. This would be an accompanied .a or a .so library.
#include "logger.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#define LOGGER_BUF_SIZE 64u
#define LOGGER_MAX_COUNT 4u
/* Full definition is visible only here. Fields can change without
* touching any caller. */
struct logger {
bool in_use;
const char *prefix;
enum logger_level level;
uint32_t written;
uint32_t dropped;
char buf[LOGGER_BUF_SIZE];
};
/* Callers cannot allocate a struct whose size they do not know,
* so the module owns the storage. */
static struct logger pool[LOGGER_MAX_COUNT];
static const char *const level_tag[] = { "E", "W", "I", "D" };
struct logger *logger_create(const char *prefix, enum logger_level level)
{
if (prefix == NULL || level > LOGGER_DEBUG) {
return NULL;
}
for (size_t i = 0; i < LOGGER_MAX_COUNT; i++) {
if (!pool[i].in_use) {
struct logger *self = &pool[i];
memset(self, 0, sizeof(*self));
self->in_use = true;
self->prefix = prefix;
self->level = level;
return self;
}
}
return NULL; /* pool exhausted */
}
void logger_destroy(struct logger *self)
{
if (self != NULL) {
memset(self, 0, sizeof(*self)); /* also clears in_use */
}
}
int32_t logger_set_level(struct logger *self, enum logger_level level)
{
if (self == NULL || level > LOGGER_DEBUG) {
return -1;
}
self->level = level;
return 0;
}
int32_t logger_log(struct logger *self, enum logger_level level, const char *msg)
{
if (self == NULL || msg == NULL || level > LOGGER_DEBUG) {
return -1;
}
if (level > self->level) {
self->dropped++;
return 0;
}
int n = snprintf(self->buf, sizeof(self->buf), "[%s] %s: %s",
level_tag[level], self->prefix, msg);
if (n < 0) {
return -1;
}
self->written++;
return n;
}
const char *logger_last(const struct logger *self)
{
return (self != NULL) ? self->buf : "";
}
uint32_t logger_dropped(const struct logger *self)
{
return (self != NULL) ? self->dropped : 0u;
}
In a context:
#include <stdio.h>
#include "logger.h"
int main(void)
{
struct logger *sys_log = logger_create("sys", LOGGER_INFO);
struct logger *motor_log = logger_create("motor", LOGGER_DEBUG);
logger_log(sys_log, LOGGER_INFO, "boot complete");
logger_log(sys_log, LOGGER_DEBUG, "this one is dropped");
logger_log(motor_log, LOGGER_DEBUG, "pwm duty 42 %");
printf("%s\n", logger_last(sys_log));
printf("%s\n", logger_last(motor_log));
printf("sys dropped=%u\n", logger_dropped(sys_log));
/* sys_log->dropped = 0; error: invalid use of incomplete type */
logger_destroy(motor_log);
logger_destroy(sys_log);
return 0;
}
The difference here is subtle, but meaningful. In the object, the struct definitions is in the header, and in opaque, in the .c file.
Singleton pattern
In a sense, a global variable, say a counter, implements a singleton pattern. Expanding on that, in some cases, it makes sense to have only one instance of an object. Given some system, if it is not acceptable, under any circumstance, to have a duplicate of an object, then singleton is the right design choise. This is the case for:
- Hardware that exists once. A systick timer, a watchdog, the interrupt controller. Note that some systems have multiple controllers, like uarts.
- System-wide services. Say a scheduler algorithm, heap allocation, non-volatile memory storage, single sink, like a console.
- Globally consistant variables. A monotonic clock, boot and trace counters.
A subsystem logger is an object. A global logger is a singleton.
Let’s look at a systick implemetation.
systick.h
#ifndef SYSTICK_H
#define SYSTICK_H
#include <stdint.h>
/* No self pointer anywhere: the one instance is implicit. */
void systick_init(void);
uint32_t systick_now(void);
void systick_isr(void); /* called from the timer interrupt */
#endif /* SYSTICK_H */
systick.c
#include "systick.h"
#include <stdbool.h>
/* The single instance lives here, invisible to callers. */
static volatile uint32_t ticks;
static bool initialized;
void systick_init(void)
{
if (initialized) {
return; /* second init is a no-op, not a second instance */
}
ticks = 0;
/* SysTick->LOAD = ...; SysTick->CTRL = ...; */
initialized = true;
}
uint32_t systick_now(void)
{
return ticks;
}
void systick_isr(void)
{
ticks++;
}
Having only one way to fetch the logger intance, from the previous example, would then make it a singleton. Note that eager initialization is prefered with singleton, so the first callers don’t race the initialization function.
As an eye opener, singleton patterns tend to happen accidentally. When some object, be it in any language, has a member, that every other object is interested of, an accidental singleton can be mistakenly created, also known as tight coupling. This can be an actual variable, or a handler to some sub-component. When a lot of objects directly access a member of some other object, modifying the central member breaks the referencing “clients”.
Factory pattern
Concisely, a factory is a function that turns a description of what is needed into a ready object, hiding which kind was chosen and how it was built. In languages with built-in polymorphism the factory simply returns a base-class reference and the language dispatches to the right variant. C has no such mechanism, so the factory and its callers must agree on a common handle type, built by hand.
logger_factory.h
#ifndef LOGGER_FACTORY_H
#define LOGGER_FACTORY_H
#include "logger.h"
enum subsystem {
SUBSYS_SYSTEM = 0,
SUBSYS_MOTOR,
SUBSYS_COOLER,
SUBSYS_COUNT,
};
struct logger *logger_for(enum subsystem id);
#endif /* LOGGER_FACTORY_H */
logger_factory.c
#include "logger_factory.h"
#include <stddef.h>
static const struct {
const char *prefix;
enum logger_level level;
} config[SUBSYS_COUNT] = {
[SUBSYS_SYSTEM] = { "sys", LOGGER_INFO },
[SUBSYS_MOTOR] = { "motor", LOGGER_DEBUG },
[SUBSYS_COOLER] = { "cooler", LOGGER_WARN },
};
static struct logger *cache[SUBSYS_COUNT];
struct logger *logger_for(enum subsystem id)
{
if (id >= SUBSYS_COUNT) {
return NULL;
}
if (cache[id] == NULL) {
cache[id] = logger_create(config[id].prefix, config[id].level);
}
return cache[id];
}
Usage:
logger_log(logger_for(SUBSYS_MOTOR), LOGGER_DEBUG, "pwm duty 42 %");
logger_log(logger_for(SUBSYS_COOLER), LOGGER_DEBUG, "dropped, cooler is WARN");
A factory is also easily scalable. Adding another logger type in the example above is straight forward. This factory selects a configuration rather than a kind, but the shape is the same: adding a subsystem is one enum entry and one table row, and no caller changes. A factory that returns genuinely different kinds behind one handle needs the inheritance pattern, which we get to below.
Callback pattern
In some case, having a single callback function, with one definition makes sense. This inverts the direction of a call. Usually a module calls down into things it depends on. With a callback, the module is handed a callback pointer by its caller and calls up into code it has never seen. The module defines the signature, the caller provides the body. This explains, how generic modules stay generic. A Sort<T> can sort any types, given it has the callback functions. An interrupt handler table dispatched to code the vendor never wrote.
In C, the callback implemetation uses void pointers. Note, that a bare function pointer has no context, so a caller has no idea who made the call. For this reason, a void *ctx is stored by the caller at registration, and returned to the caller on every call. This is the contract between the two end points, so every caller knows the callback execution was turthfully put out by the exact caller.
Continuing the logger examples, one might want to choose, where the logger stores its output.
logger.h
/* The callback type: what the logger will call to get a line out.
* `ctx` is handed back untouched so the callee can find its own state. */
typedef int32_t (*logger_sink_fn)(void *ctx, const char *line, size_t len);
int32_t logger_set_sink(struct logger *self, logger_sink_fn fn, void *ctx);
logger.c
struct logger {
/* ... */
logger_sink_fn sink; /* where lines go */
void *sink_ctx; /* opaque to the logger */
char buf[LOGGER_BUF_SIZE];
};
int32_t logger_set_sink(struct logger *self, logger_sink_fn fn, void *ctx)
{
if (self == NULL) {
return -1;
}
self->sink = fn;
self->sink_ctx = ctx;
return 0;
}
int32_t logger_log(struct logger *self, enum logger_level level, const char *msg)
{
/* ... level check and snprintf into self->buf as before ... */
if (self->sink == NULL) {
return 0; /* no sink registered: silently drop */
}
/* The logger knows nothing about UARTs, files or ring buffers.
* It just calls back. */
return self->sink(self->sink_ctx, self->buf, len);
}
main.c
/* Sink 1: stdio. ctx is a FILE *. */
static int32_t sink_stdio(void *ctx, const char *line, size_t len)
{
return (int32_t)fwrite(line, 1, len, (FILE *)ctx);
}
/* Sink 2: a ring buffer owned by the caller. ctx is the ring. */
struct ring {
char data[128];
size_t head;
};
static int32_t sink_ring(void *ctx, const char *line, size_t len)
{
struct ring *r = ctx;
for (size_t i = 0; i < len; i++) {
r->data[r->head] = line[i];
r->head = (r->head + 1) % sizeof(r->data);
}
return (int32_t)len;
}
int main(void)
{
struct ring motor_ring = { .head = 0 };
struct logger *sys_log = logger_create("sys", LOGGER_INFO);
struct logger *motor_log = logger_create("motor", LOGGER_DEBUG);
logger_set_sink(sys_log, sink_stdio, stdout); /* same logger code ... */
logger_set_sink(motor_log, sink_ring, &motor_ring); /* ... two destinations */
logger_log(sys_log, LOGGER_INFO, "boot complete");
logger_log(motor_log, LOGGER_DEBUG, "pwm duty 42 %");
return 0;
}
One logger logs to a ring, the other to a file. With a typedef int32_t (*logger_sink_fn)(void *, const char *, size_t); the code becomes more readable. A sink, that logs inside its callback, recurses into the logger.
A message type handler is a common use of callbacks. Or an event in an event loop. Modularity comes free.
The opaque pattern keeps the caller from seeing inside the module, and the callback pattern keeps the module from seeing outside itself. Together they give a module with a hard boundary in both directions.
Inheritance pattern
In any language, inheritance boils down to two functionalities:
- Structural. A derived object contains a complete base object, so a pointer to the derived can be used where a pointer to the base is expected.
- Behavioural. Calling a method through a base pointer runs the derived version, in C++ this means vtable, virtual dispatch.
In C, a few middle steps are needed for the inheritance pattern.
Step one: embed the base as the first member.
struct sink { /* base */
const struct sink_ops *ops;
uint32_t bytes_written;
};
struct ring_sink { /* derived */
struct sink base; /* MUST be first */
char data[128];
size_t head;
};
The C standard guarantees that a pointer to a struct, suitably converted, points to its first member, and vice versa. So (struct sink *)&ring and (struct ring_sink *)base_ptr are both well defined, with no padding in front and no undefined behaviour. That one guarantee is the whole mechanism. Upcast by taking &self->base, downcast by casting the base pointer back. If the base is not first, you need offsetof arithmetic, which is what the Linux kernel’s container_of macro does.
Step two: a table of function pointers for dispatch
struct sink_ops {
int32_t (*write)(struct sink *self, const char *line, size_t len);
void (*flush)(struct sink *self);
};
Each derived type fills one static const table and points base.ops at it. Calls go through the base: self->ops->write(self, ...). This is exactly what a C++ compiler generates for a class with virtual functions, down to the name: the vtable. Keeping one shared const table per type rather than function pointers in every instance saves RAM and keeps the table in flash.
In one view, this is the callback pattern applied systematically. One callback is a function pointer. A vtable is a struct of them with a fixed contract and the object itself as context.
One derived type, ring_sink.c:
static int32_t ring_write(struct sink *base, const char *line, size_t len)
{
struct ring_sink *self = (struct ring_sink *)base; /* downcast */
for (size_t i = 0; i < len; i++) {
self->data[self->head] = line[i];
self->head = (self->head + 1) % sizeof(self->data);
}
return (int32_t)len;
}
static const struct sink_ops ring_ops = {
.write = ring_write,
.flush = NULL,
};
struct sink *ring_sink_init(struct ring_sink *self)
{
memset(self, 0, sizeof(*self));
self->base.ops = &ring_ops;
return &self->base; /* upcast */
}
Inheriting multiple interfaces mean multiple ops tables.
The factory section promised that returning “genuinely different kinds behind one handle” needs inheritance. This is it: a factory can now return struct sink * and choose ring_sink or stdio_sink internally, and the caller is none the wiser.
Bridge pattern
Bridging ties functionality together. In inheritance, a sematic is tied to some object, like ring sink is a type of sink, whereas with a bridge some object has some property, like a sensor can have some bus, which can be i2c, spi etc.
Below is an example of bus abstraction. The bus implementations are left out deliberately.
bus.h
struct bus;
struct bus_ops {
int32_t (*read_reg)(struct bus *self, uint8_t reg, uint8_t *buf, size_t len);
int32_t (*write_reg)(struct bus *self, uint8_t reg, const uint8_t *buf, size_t len);
};
struct bus {
const struct bus_ops *ops;
};
bme280.h
struct bme280 {
struct bus *bus; /* the bridge: a pointer, not an embedded base */
uint8_t chip_id;
};
int32_t bme280_init(struct bme280 *self, struct bus *bus);
int32_t bme280_set_mode(struct bme280 *self, uint8_t mode);
bme280.c
/* Not one line here knows whether this is I2C or SPI. */
int32_t bme280_init(struct bme280 *self, struct bus *bus)
{
self->bus = bus;
int32_t rc = bus->ops->read_reg(bus, BME280_REG_ID, &self->chip_id, 1);
if (rc != 0) {
return rc;
}
return (self->chip_id == BME280_CHIP_ID) ? 0 : -2;
}
int32_t bme280_set_mode(struct bme280 *self, uint8_t mode)
{
return self->bus->ops->write_reg(self->bus, BME280_REG_CTRL_MEAS, &mode, 1);
}
In context:
struct i2c_bus i2c;
struct spi_bus spi;
struct bme280 env_a, env_b;
bme280_init(&env_a, i2c_bus_init(&i2c, 0x76));
bme280_init(&env_b, spi_bus_init(&spi, 4));
Output:
sensor A on I2C:
i2c[0x76]: read reg 0xd0, 1 byte(s)
i2c[0x76]: write reg 0xf4 = 0x27
sensor B on SPI:
spi[cs4]: read reg 0xd0 (tx 0xd0), 1 byte(s)
spi[cs4]: write reg 0xf4 (tx 0x74) = 0x27
both report chip id 0x60 / 0x60
Pitfalls
- The implementation interface has to be minimal. read_reg and write_reg is the right size for a bus. If it grows to twenty functions the implementations become expensive to write and the bridge stops paying for itself.
- Lifetime. The abstraction holds a pointer it does not own. The bus must outlive every sensor on it.
- Shared implementations need their own locking. Two sensors on one I2C bus from two threads is a bus-level problem, and it belongs in the bus implementation, not the sensor driver.
Return value pattern
C has no exceptions. A function that can fail has exactly one way to say so: its return value. The return value pattern is the discipline of using that one channel consistently across the whole code base, so that every call site looks the same and every failure has a path back to someone who can act on it.
The pattern has three parts.
Status goes in the return value, results go in out-parameters. A function returns a status code and nothing else. Anything it produces is written through a pointer the caller provides. This keeps the two separate: the caller cannot mistake a result for an error, and there is no magic value like -1 or NULL that means “failed” in one function and “empty” in another.
One error type for everything. Every module returns the same enum. Zero means success, every other value is a failure, and the values never collide. When logger_log propagates an error from a sink, the caller receives the sink’s error unchanged, and can print it with the same function it uses for every other error in the system.
Check every return. The compiler will not help you here, so the convention has to. A status that is not checked is a failure that will surface somewhere else, later, as something that looks unrelated.
Let’s apply this to the logger. First the shared error type:
err.h
/* One error type for the whole code base. Zero is success, everything
* else is a failure, and the values never collide between modules. */
enum err {
ERR_OK = 0,
ERR_INVAL, /* bad argument */
ERR_NOMEM, /* pool or heap exhausted */
ERR_BUSY, /* resource held by someone else */
ERR_IO, /* the hardware said no */
ERR_TIMEOUT,
};
const char *err_str(enum err e);
Now the logger interface. Compare this with the opaque version: logger_create used to return the pointer and signal failure with NULL. Now the pointer is an out-parameter and the return value says why it failed. The sink callback follows the same rule, so an error from the hardware can travel all the way up.
logger.h
typedef enum err (*logger_sink_fn)(void *ctx, const char *line, size_t len);
struct logger;
/* Status comes back in the return value. Results come back through
* out-parameters, which by convention go first. */
enum err logger_create(struct logger **out, const char *prefix, enum logger_level level);
void logger_destroy(struct logger *self);
enum err logger_set_sink(struct logger *self, logger_sink_fn fn, void *ctx);
enum err logger_log(struct logger *self, enum logger_level level, const char *msg);
enum err logger_stats(const struct logger *self, uint32_t *written, uint32_t *dropped);
logger.c, one function implementation:
enum err logger_create(struct logger **out, const char *prefix, enum logger_level level)
{
if (out == NULL || prefix == NULL || level > LOGGER_DEBUG) {
return ERR_INVAL;
}
*out = NULL; /* never leave an out-param undefined */
for (size_t i = 0; i < LOGGER_MAX_COUNT; i++) {
if (!pool[i].in_use) {
/* ... initialise pool[i] ... */
*out = &pool[i];
return ERR_OK;
}
}
return ERR_NOMEM;
}
In context:
rc = logger_create(&third, "cooler", LOGGER_INFO);
printf("third logger: %s\n", err_str(rc)); /* pool holds two */
rc = logger_log(sys, LOGGER_INFO, "boot complete");
printf("log: %s\n", err_str(rc));
uart_ready = 0;
rc = logger_log(sys, LOGGER_INFO, "this will not get out");
printf("log: %s\n", err_str(rc)); /* sink's error, verbatim */
rc = logger_log(NULL, LOGGER_INFO, "no logger");
printf("log: %s\n", err_str(rc));
third logger: out of memory
[I] sys: boot complete
log: ok
log: busy
log: invalid argument
A few conventions that make the pattern hold up at scale:
- Put out-parameters first or last, but pick one and never mix. The examples here put them first, which is the Zephyr and Windows convention. POSIX tends to put them last.
- Make
ERR_OKzero. Then if (rc) reads as “if it failed”, and a zeroed struct is in a valid state. - Use negative values if you need to coexist with POSIX style code that returns a count on success. Zephyr does this with -EINVAL and friends, which lets a function return either a byte count or an error in the same int. It costs you the ability to return the full unsigned range.
- Mark functions whose status must not be ignored with
__attribute__((warn_unused_result))on GCC and Clang. It is the closest C gets to a checked exception. - Do not use
errno. It is a global, which is exactly the shared state the object pattern was built to avoid, and it has the re-entrancy problems described there.
The return value pattern is the least glamorous one in this list, and the one with the highest payoff. It is one pattern I find mandatory in embedded context. Every other pattern here produces a function. This one decides what every one of those functions tells you when it does not work.
Patterns related to concurrency
Previous examples focus primarily on single-thread context. If you can get away with using a single thread implementations, then the examples are suitable as they are. In a more busy system, multiple actors access the same data structures, calling the same fuctions, in which case the code paths call for thread safety: atomic reads, semaphores, mutexes.
Let’s look at them briefly.
- Concurrency pattern, the design step
- Spinlock pattern
- Semaphore pattern
- Mutex pattern
- Conditional pattern
The first one is a design decision. The remaining four are the primitives it uses.
Concurrency pattern
The concurrency pattern is the design step before any lock: deciding which execution context owns each piece of state, and how the others reach it. The four patterns after this one are the primitives used when that decision still leaves something shared.
When two execution streams manipulate a variable, it is called concurrent access. What causes unwanted behavior in concurrency, is when manipulation order is not in control of any stream, in which case, the streams “race” for control, a well understood event in concurrent access. As the topic is well understood, and covered in literature, a simple case is presented. Here there are distict roles: a producer and a consumer.
struct spsc {
uint32_t buf[SPSC_SIZE];
atomic_uint head; /* written by producer only */
atomic_uint tail; /* written by consumer only */
};
static inline bool spsc_push(struct spsc *q, uint32_t v)
{
unsigned h = atomic_load_explicit(&q->head, memory_order_relaxed);
unsigned t = atomic_load_explicit(&q->tail, memory_order_acquire);
if (h - t == SPSC_SIZE) {
return false; /* full: caller decides, usually drop + count */
}
q->buf[h % SPSC_SIZE] = v;
atomic_store_explicit(&q->head, h + 1, memory_order_release);
return true;
}
Spinlock pattern
A spinlock is the smallest lock there is: one word, and a loop that retries an atomic test-and-set until it wins. The holder never sleeps, and the waiter never sleeps either, it burns cycles until the lock frees. That makes it the only lock that is legal in an interrupt handler, and the right lock when the protected section is a handful of instructions and shorter than a context switch.
On a single core, a spinlock degenerates into a critical section: there is no other core to spin against, so the implementation simply masks interrupts. This is why bare-metal Cortex-M code uses __disable_irq() and the RTOS kernels use taskENTER_CRITICAL() for the same job. On multicore parts like RP2040 or STM32H7 it is a real spinlock, backed by hardware.
Rules: hold it for nanoseconds, never call anything while holding it, never block while holding it.
pthread_spin_lock(&spin);
fast_counter++;
pthread_spin_unlock(&spin);
Semaphore pattern
A semaphore is a counter with blocking. give increments it, take decrements it or waits for it to be nonzero. It has no owner, so anyone may give, including an interrupt handler. That one property decides its job: a semaphore is for signalling, not for protecting data.
The two uses that matter in firmware:
- Binary semaphore as an ISR-to-task wake-up. The ISR gives, the task takes. The task sleeps until there is work, the ISR exits in microseconds. Every RTOS has a FromISR variant for exactly this call.
- Counting semaphore as a resource pool. Initialise to the number of DMA channels or buffers, take one to use, give it back when done. Takers block when the pool is empty.
Using a binary semaphore as a mutex works until it does not: there is no priority inheritance and nothing stops the wrong task releasing it.
sem_post(&items); /* producer or ISR: "one more item" */
sem_wait(&items); /* consumer: block until an item exists */
Mutex pattern
A mutex protects data. It has an owner, and only the owner may release it. A task that finds it taken goes to sleep and the scheduler runs something else, so holding one for longer stretches is fine, and the cost of taking it is a potential context switch. For that reason it cannot be used from an interrupt handler, where sleeping is not an option.
Because it has an owner, the kernel can do things a plain lock cannot: detect double-lock and unlock-by-stranger, and, importantly on an RTOS, apply priority inheritance. If a low priority task holds a mutex that a high priority task is waiting for, the holder is temporarily boosted so a medium task cannot starve both. This is the fix for the priority inversion that famously halted Mars Pathfinder, and it is the main reason to use a mutex instead of a binary semaphore for data protection.
Rules: one mutex per invariant, take and release in the same function, never hold two unless the order is written down.
pthread_mutex_lock(&mtx);
shared_state += 10;
pthread_mutex_unlock(&mtx);
Conditional pattern
A condition variable lets a task sleep until some predicate over shared state becomes true, for example “the queue is not empty” or “the firmware image is fully received”. It is always paired with a mutex: the mutex protects the state, the condition variable is the wait list.
The call that makes it work is wait. It atomically releases the mutex and puts the task to sleep, then re-acquires the mutex before returning. Without that atomicity there is a window where the signal arrives after the check and before the sleep, and the waiter sleeps forever. The waiter must loop on the predicate, because the standard permits spurious wakeups and because another task may have consumed the state first.
/* waiter */
pthread_mutex_lock(&mtx);
while (!ready) { /* always a loop, never an if */
pthread_cond_wait(&cv, &mtx); /* atomically unlocks + sleeps */
}
/* ... ready is true and mtx is held ... */
pthread_mutex_unlock(&mtx);
/* signaller */
pthread_mutex_lock(&mtx);
ready = true; /* change the predicate ... */
pthread_cond_signal(&cv); /* ... then wake one waiter */
pthread_mutex_unlock(&mtx);
Conclusion
Internalizing these design patterns, and knowing the best options for a given task coms with expertise. I suggest implementing system components with different blueprints, and take your time to understand the pros and cons of each one. Let’s pay a little respect for the patterns, and their creators. Having a clear grasp on them makes engineering tasks a lot less cumbersome.
References
- Design Patterns for Embedded Systems in C (geeksforgeeks.org)
- Martin Schröders book, Embedded C Programming Design Patterns