linux-sysprog · intermediate · ~12 min

Build a tiny thread-safe counter type

Wrap a mutex + state in a tiny opaque struct.

Challenge

Implement four functions for a thread-safe long counter:

typedef struct ts_counter ts_counter_t;
ts_counter_t *tsc_new(void);
void tsc_inc(ts_counter_t *c);
long tsc_value(ts_counter_t *c);
void tsc_free(ts_counter_t *c);

Internally use a pthread_mutex_t to protect a long field. tsc_value must return the current value as observed under the lock.

Why this matters

Encapsulate a primitive into a reusable thread-safe API — the building block of every server's stats counter.

Starter code

#include <pthread.h>
#include <stddef.h>
struct ts_counter;
typedef struct ts_counter ts_counter_t;
ts_counter_t *tsc_new(void) { return NULL; }
void tsc_inc(ts_counter_t *c) { (void)c; }
long tsc_value(ts_counter_t *c) { (void)c; return 0; }
void tsc_free(ts_counter_t *c) { (void)c; }

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.