CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Thread-Local Cleanup

Typedefs

typedef void(* TLSCleanupCB) (void *data)
 

Functions

CX_C void thrRegisterCleanup (TLSCleanupCB cb, void *data)
 

Detailed Description

Lets code register a callback to run automatically when the calling thread exits, so thread-local resources can be freed without every thread entry point having to know about them.

A typical use is lazily-allocated thread-local state: allocate it on first use, and register a cleanup callback at the same time so it gets freed when the thread ends, even if the thread never explicitly tears it down.

static _Thread_local MyPerThreadData* data;
static void myDataCleanup(void* unused)
{
xaDestroy(&data);
}
MyPerThreadData* getMyData(void)
{
if (!data) {
data = xaAllocStruct(MyPerThreadData);
thrRegisterCleanup(myDataCleanup, NULL);
}
return data;
}
CX_C void thrRegisterCleanup(TLSCleanupCB cb, void *data)
#define xaDestroy(ptr)
Definition xalloc.h:245
#define xaAllocStruct(typn,...)
Definition xalloc.h:213

A callback must be registered from the thread it applies to. There is no way to register a cleanup callback for a different thread.

Typedef Documentation

◆ TLSCleanupCB

typedef void(* TLSCleanupCB) (void *data)

void (*TLSCleanupCB)(void *data)

Callback invoked when the registering thread exits.

Parameters
dataThe pointer passed to thrRegisterCleanup() alongside this callback

Definition at line 45 of file tlscleanup.h.

Function Documentation

◆ thrRegisterCleanup()

CX_C void thrRegisterCleanup ( TLSCleanupCB  cb,
void *  data 
)

Register a callback to run when the calling thread exits

The callback is invoked once, on the same thread that registered it, as that thread exits. Multiple callbacks may be registered by the same thread; they run in the order they were registered.

Parameters
cbCallback to invoke on thread exit
dataValue passed to the callback