TINFO(3)

NAME
tinfo - self-(de)allocating thread-local data structures

LIBRARY
PDEL Library (libpdel, -lpdel)

SYNOPSIS
#include <pthread.h>
#include <pdel/util/tinfo.h>
TINFO_INIT(type, mtype, initfunc);
void *
tinfo_get(struct tinfo *t);
int
tinfo_set(struct tinfo *t, const void *data);
int
tinfo_set_nocopy(struct tinfo *t, void *data);

DESCRIPTION
These functions provide support for thread-local data structures defined by structs(3) types that are automatically initialized and destroyed. A thread-local data structure is described by a static or global struct tinfo; each such structure must be initialized with the TINFO_INIT() macro. For example:

    static struct tinfo foo_info
            = TINFO_INIT(&foo_type, "foo", fooinit);

type is the structs(3) type for the data structure, mtype is the typed_mem(3) type used to allocate memory to hold each thread's instance, and initfunc is an optional instance initializer function of this type:

    typedef int tinfo_init_t(struct tinfo *t, void *data);

initfunc() should initialize the data structure pointed to by data as an instance of type (which will also be available as t->type). The memory pointed to by data will have been allocated with typed_mem(3) type mtype but will be otherwise uninitialized. If initfunc is NULL, then structs_init(3) is used to initialize the data structure to the default value defined by type.

Instances of tinfo thread-local data structure are automatically destroyed when the associated thread exits, by calling structs_free(type, NULL, data) and then FREE(mtype, data).

tinfo_get() returns the current thread's instance of the data structure. If this is the thread's first invocation of tinfo_get(), a new instance is automatically allocated and initialized. The caller should free the returned value, but may modify it in a way consistent with its structs(3) type.

tinfo_set() sets the current thread's data structure instance to be a copy of data, made using structs_get(3). The original data is unmodified and remains the caller's responsibility to free. Any existing thread-local data structure instance is automatically replaced and freed.

tinfo_set_nocopy() is equivalent to tinfo_set() except that no copy of data is made; therefore, data must point to heap memory allocated with typed_mem(3) type mtype (also available as t->mtype) and the caller should not dereference data once tinfo_set_nocopy() has returned successfully.

Both tinfo_set() and tinfo_set_nocopy() may take a NULL data parameter; this causes any existing thread-local data structure instance to be freed so that the next call to tinfo_get() will cause a new instance to be constructed.

RETURN VALUES
tinfo_get(), tinfo_set(), and tinfo_set_nocopy() return NULL or -1 with errno set appropriately to indicate an error.

SEE ALSO
libpdel(3), structs(3), typed_mem(3)

HISTORY
The PDEL library was developed at Packet Design, LLC. http://www.packetdesign.com/

AUTHORS
Archie Cobbs <archie@freebsd.org>