### Storage for Thread Specific Data

The pthread package provides the ability to allocate per-thread global storage using per-thread data keys. That is, an application can create storage that has global scope within a thread but which is private to each instance of that thread. To do this, the application creates a global data key by calling pthread_keycreate( ). Each thread then typically allocates storage of the required type and associates this instance with the global key by calling pthread_setspecific( ). Routines that need to access the per-thread storage do so by calling pthread_getspecific( ), which returns the address of the thread's private instance.

The following code fragments show a sample model of per-thread-data key use:

/* Declare global data key storage */
pthread_key_t key;
main()
{ . . .
.
.
.
/* Create exactly one instance of the key. You could also use */
/* a pthread_once() routine... */
status = pthread_keycreate(&key, (pthread_destructor_t) destroy);
.
.
.
/* Start some threads... */
.
.
.
}
/* The following routines are called in each of the threads. */
/* They access the thread's private instance of the "global" */
/* value. */
/* The following routine sets the value to a thread-specific */
/* value... */
void write_global(mytype value)
{
mytype *global_var;
global_var = (mytype*) malloc(sizeof(mytype));
pthread_setspecific(key, (pthread_addr_t)global_var);
*global_var = value;
}
/* The following routine returns the thread-specific value ... */
mytype read_global()
{
mytype *global_var;
/* Note the extra indirection; pthread_getspecific() returns */
/* the address of the thread's private instance of the */
/* storage... */
pthread_getspecific(key, (pthread_addr_t*)&global_var);
return (*global_var);
}

###