PTHREAD_KEY_CREATE(3POSIX)
β¨ PROLOG β¨
okay so before we even get into it β this manual page is part of the POSIX Programmer's Manual, bestie. That's the tea. π«
The Linux implementation of this interface may differ (so like, go read the corresponding Linux manual page for the actual Linux behavior, iykyk), or honestly the interface may not be implemented on Linux at all. π
π NAME π
pthread_key_create β thread-specific data key creation. yes that's the whole vibe. it makes keys. for threads. slay.
πΈ SYNOPSIS πΈ
#include <pthread.h>
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
π¦ DESCRIPTION π¦
so the pthread_key_create() function shall create a thread-specific data key that's visible to all threads in the process. π
key values handed to you by pthread_key_create() are opaque objects β literally just little tokens used to locate thread-specific data. even though the same key value can be used by different threads, the values bound to that key by pthread_setspecific() are maintained on a per-thread basis and they persist for the life of the calling thread. periodt.
upon key creation, the value NULL shall be associated with the new key in all active threads. and upon thread creation, the value NULL shall be associated with all defined keys in that new thread. so like, everyone starts fresh with NULL. it's giving clean slate energy. β¨
an optional destructor function may be associated with each key value. at thread exit, if a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated with that key, then:
- the value of the key is set to
NULL - and then the function pointed to is called with the previously associated value as its sole argument
the order of destructor calls is unspecified if more than one destructor exists for a thread when it exits. no promises on the order, bestie. π
now here's the part that goes hard: if, after all the destructors have been called for all non-NULL values with associated destructors, there are still some non-NULL values with associated destructors, then the whole process is repeated. and if, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor calls for outstanding non-NULL values, there are still some non-NULL values with associated destructors, implementations may stop calling destructors, or they may keep calling destructors until no non-NULL values with associated destructors exist β even though this might result in an infinite loop. π not the infinite loop. but that's literally what the spec says.
π RETURN VALUE π
if successful, the pthread_key_create() function shall store the newly created key value at *key and shall return zero. otherwise, an error number shall be returned to indicate the error. classic.
π₯ ERRORS π₯
the pthread_key_create() function shall fail if:
EAGAINβ the system lacked the necessary resources to create another thread-specific data key, or the system-imposed limit on the total number of keys per process{PTHREAD_KEYS_MAX}has been exceeded. πENOMEMβ insufficient memory exists to create the key. π
and just so we're clear: the pthread_key_create() function shall not return an error code of [EINTR].
the following sections are informative.
π EXAMPLES π
okay this example is actually so cute, it demonstrates a function that initializes a thread-specific data key when it's first called, and associates a thread-specific object with each calling thread, initializing that object when necessary:
static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;
static void
make_key()
{
(void) pthread_key_create(&key, NULL);
}
func()
{
void *ptr;
(void) pthread_once(&key_once, make_key);
if ((ptr = pthread_getspecific(key)) == NULL) {
ptr = malloc(OBJECT_SIZE);
...
(void) pthread_setspecific(key, ptr);
}
...
}
note that the key has to be initialized before pthread_getspecific() or pthread_setspecific() can be used. the pthread_key_create() call could either be explicitly made in a module initialization routine, or it can be done implicitly by the first call to a module, like in this example. any attempt to use the key before it's initialized is a programming error, which makes the code below incorrect. π¨
static pthread_key_t key;
func()
{
void *ptr;
/* KEY NOT INITIALIZED!!! THIS WILL NOT WORK!!! */
if ((ptr = pthread_getspecific(key)) == NULL &&
pthread_setspecific(key, NULL) != 0) {
pthread_key_create(&key, NULL);
...
}
}
do NOT do that second one. it's giving chaos. π ββοΈ
π§ APPLICATION USAGE π§
None.
literally none. that's the whole section. iconic tbh.
π RATIONALE π
Destructor Functions
normally, the value bound to a key on behalf of a particular thread is a pointer to storage allocated dynamically on behalf of the calling thread. the destructor functions specified with pthread_key_create() are intended to be used to free this storage when the thread exits. π
thread cancellation cleanup handlers cannot be used for this purpose, because thread-specific data may persist outside the lexical scope in which the cancellation cleanup handlers operate. so like, different tool, different job.
if the value associated with a key needs to be updated during the lifetime of the thread, it may be necessary to release the storage associated with the old value before the new value is bound. although the pthread_setspecific() function could do this automatically, this feature is not needed often enough to justify the added complexity. instead, the programmer is responsible for freeing the stale storage:
pthread_getspecific(key, &old);
new = allocate();
destructor(old);
pthread_setspecific(key, new);
Note: the above example could leak storage if run with asynchronous cancellation enabled. no such problems occur in the default cancellation state if no cancellation points occur between the get and set. so like, watch out bestie. π«Ά
there is no notion of a destructor-safe function. if an application does not call pthread_exit() from a signal handler, or if it blocks any signal whose handler may call pthread_exit() while calling async-unsafe functions, all functions may be safely called from destructors. okay so that's the rule, no cap.
Non-Idempotent Data Key Creation
so there were literally requests to make pthread_key_create() idempotent with respect to a given key address parameter. that would let applications call pthread_key_create() multiple times for a given key address and be guaranteed that only one key would be created. β¨
doing so would require the key value to be previously initialized (possibly at compile time) to a known null value, and would require that implicit mutual-exclusion be performed based on the address and contents of the key parameter, in order to guarantee that exactly one key would be created.
unfortunately π the implicit mutual-exclusion would not be limited to only pthread_key_create(). on many implementations, implicit mutual-exclusion would also have to be performed by pthread_getspecific() and pthread_setspecific() in order to guard against using incompletely stored or not-yet-visible key values. this could significantly increase the cost of important operations, particularly pthread_getspecific(). and like, we don't want that.
thus, this proposal was rejected. the pthread_key_create() function performs no implicit synchronization. it is the responsibility of the programmer to ensure that it is called exactly once per key before use of the key. several straightforward mechanisms can already be used to accomplish this, including:
- calling explicit module initialization functions
- using mutexes
- using
pthread_once()
this places no significant burden on the programmer, introduces no possibly confusing ad hoc implicit synchronization mechanism, and potentially allows commonly used thread-specific data operations to be more efficient. π the way that's actually a good design decision? obsessed.
β FUTURE DIRECTIONS β
None.
π SEE ALSO π
pthread_getspecific()pthread_key_delete()- The Base Definitions volume of POSIX.1β2017,
<pthread.h>
π COPYRIGHT π
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
okay that's the whole page bestie, you made it to the end, proud of you π₯Ήπ this one's from IEEE/The Open Group, 2017, and yeah it's the PTHREAD_KEY_CREATE(3POSIX) page, mwah, go create some keys responsibly. β¨ππ
π¦ where this page comes from
- debian bookworm: manpages-posix-dev 2017a-2 Β· Other
- debian trixie: manpages-posix-dev 2017a-2 Β· Other
- ubuntu jammy: manpages-posix-dev 2017a-2 Β· Other
- ubuntu noble: manpages-posix-dev 2017a-2 Β· Other
- ubuntu resolute: manpages-posix-dev 2017a-2build1 Β· Other
- ubuntu stonking: manpages-posix-dev 2017a-2.1 Β· Other
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms