linux-sysprog · intermediate · ~12 min
Wrap a mutex + state in a tiny opaque struct.
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.
Encapsulate a primitive into a reusable thread-safe API — the building block of every server's stats counter.
#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; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.