linux-sysprog · beginner · ~10 min
The once-only semantics of pthread_once.
pthread_once(&control, init_fn) ensures init_fn is
called exactly once across all threads that invoke it.
Simulate the semantics with a state machine. Given an array of N calls
(each a 1 in the array means 'a thread invoked pthread_once at this index'),
return the index that actually ran init_fn. The semantics:
init_fn.Implement int once_init_run_index(const int *calls, int n) returning the
index that runs init_fn, or -1 if no call was made.
pthread_once is the canonical 'initialise this lazily, exactly once, across all threads' primitive. Tracing through its semantics builds intuition.
Array of 0/1 calls + length.
Index that runs, or -1.
Find the first 1.
int once_init_run_index(const int *calls, int n) { /* TODO */ (void)calls; (void)n; return -1; }
Returning the LAST call.
All zeros. Empty array. First index is 1.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.