Multithreaded Programming Guide

Creating a Thread-Specific Data Key

thr_keycreate(3C) allocates a key that is used to identify thread-specific data in a process. The key is global to all threads in the process. Each thread binds a value to the key when the key gets created.

Except for the function names and arguments, thread-specific data is the same for Solaris threads as thread-specific data is for POSIX threads. The synopses for the Solaris functions are described in this section. For POSIX threads, see pthread_key_create Syntax.

thr_keycreate Syntax

#include <thread.h>

int thr_keycreate(thread_key_t *keyp,
    void (*destructor) (void *value));

keyp independently maintains specific values for each binding thread. Each thread is initially bound to a private element of keyp that allows access to its thread-specific data. Upon key creation, a new key is assigned the value NULL for all active threads. Additionally, upon thread creation, all previously created keys in the new thread are assigned the value NULL.

An optional destructor function can be associated with each keyp. Upon thread exit, if a keyp has a non-NULL destructor and the thread has a non-NULL value associated with keyp , the destructor is called with the currently associated value. If more than one destructor exists for a thread when it exits, the order of destructor calls is unspecified.

thr_keycreate Return Values

thr_keycreate() returns 0 if successful. When any of the following conditions is detected, thr_keycreate() fails and returns the corresponding value.



The system does not have the resources to create another thread-specific data key, or the number of keys exceeds the per-process limit for PTHREAD_KEYS_MAX.



Insufficient memory is available to associate value with keyp.