linux-sysprog · beginner · ~10 min

One-shot init: which call performs the work?

The once-only semantics of pthread_once.

Challenge

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:

  • The first call (lowest index with value 1) runs init_fn.
  • All other calls return without running it.

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.

Why this matters

pthread_once is the canonical 'initialise this lazily, exactly once, across all threads' primitive. Tracing through its semantics builds intuition.

Input format

Array of 0/1 calls + length.

Output format

Index that runs, or -1.

Constraints

Find the first 1.

Starter code

int once_init_run_index(const int *calls, int n) { /* TODO */ (void)calls; (void)n; return -1; }

Common mistakes

Returning the LAST call.

Edge cases to handle

All zeros. Empty array. First index is 1.

Complexity

O(n).

Background lessons

Up next

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