DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Threads

Thread-specific data

Historically, programs have used the static or extern storage classes to save data that must be preserved between function calls. This practice is no longer valid when many threads in the same process may run a given function concurrently and reference one static or extern variable by name. Values will not be preserved across function calls if one thread modifies a value left by another.


NOTE: In contrast, since each thread gets a unique stack, variables of the auto storage class are implicitly unique.

The facility for ``thread-specific'' data provides a solution to this problem.

The access functions have the following syntax:

   int  thr_setspecific(thread_key_t key, void *data);
   int  thr_getspecific(thread_key_t key; void **value);

A key value must be created by the thr_keycreate(3thread) function

   int thr_keycreate(
   	thread_key_t *key,
   	void         (*destructor)(void *data)
   );
where

key
This is the address where the newly valid key value will be deposited.

destructor
specifies a function that will be called on the exit of any thread that has used the key for data storage. This function should recover any space that has been used to store thread-specific data. When called, this function receives one argument, the data address that the thread gave as the second argument to thr_setspecific(3thread).


NOTE: The key can be created (or later removed) by threads other than those that use the key for data storage. The using threads need only have access to the key value by function argument, global variable, or other means.

If a particular key value is needed for only a particular phase of a program (perhaps initialization) it can be deallocated by thr_keydelete(3thread).

For efficiency, it is best to minimize the number of keys used in an application.


Next topic: Threads and signals
Previous topic: Detached threads

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004