CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Lazy Initialization

Data Structures

struct  LazyInitState
 State tracker for lazy initialization. More...
 

Typedefs

typedef struct LazyInitState LazyInitState
 State tracker for lazy initialization.
 
typedef void(* LazyInitCallback) (void *userData)
 

Functions

void lazyInit (LazyInitState *state, LazyInitCallback initfunc, void *userData)
 

Detailed Description

Provides thread-safe lazy initialization that ensures an initialization function is called exactly once, even when multiple threads attempt initialization simultaneously. Once initialized, the overhead is minimal (single boolean check).

The lazy init system uses atomic operations and spin-waiting to coordinate between threads. The first thread to reach the initialization point executes the callback, while concurrent threads spin until initialization completes. After the first initialization, subsequent calls only perform a fast boolean check.

Example:

static LazyInitState configState;
static Config *globalConfig;
static void initConfig(void *data) {
globalConfig = loadConfigFromDisk();
}
void useConfig() {
lazyInit(&configState, initConfig, NULL);
// globalConfig is now guaranteed to be initialized
processConfig(globalConfig);
}
void lazyInit(LazyInitState *state, LazyInitCallback initfunc, void *userData)
Definition lazyinit.h:69
State tracker for lazy initialization.
Definition lazyinit.h:40

Typedef Documentation

◆ LazyInitCallback

typedef void(* LazyInitCallback) (void *userData)

Callback function type for lazy initialization

Parameters
userDataOptional user data passed through from lazyInit()

Definition at line 48 of file lazyinit.h.

Function Documentation

◆ lazyInit()

void lazyInit ( LazyInitState state,
LazyInitCallback  initfunc,
void *  userData 
)
inline

void lazyInit(LazyInitState *state, LazyInitCallback initfunc, void *userData)

Ensures the initialization callback is executed exactly once in a thread-safe manner.

When multiple threads call this function concurrently with the same state:

  • The first thread executes the callback
  • Other threads spin-wait until initialization completes
  • All threads proceed only after initialization finishes

Once initialized, subsequent calls only check a boolean flag with minimal overhead. The state must remain valid for the lifetime of the lazy-initialized resource.

Parameters
statePointer to lazy initialization state (must be zero-initialized)
initfuncCallback to execute exactly once
userDataOptional user data passed to the callback

Definition at line 69 of file lazyinit.h.