In a multi-threaded environment, data space is shared by all threads. Generally, global variables are shared by all threads.
Sometimes it is necessary to provide global variables private to the thread:
-Cross-function access (global );
-Valid only in a thread (private ).
For exampleProgramEach thread may need to maintain a linked list. The maintenance means are the same, but the data in the linked list is different.
Such a data structure can be maintained by the POSIX thread library, known as thread specific data (TSD.
# Ifdef Win32 # include <windows. h> # define sleep (MS) # else if defined (Linux) # include <stdio. h> # define sleep (MS) # endif # include <pthread. h> pthread_key_t key; void echomsg (void * value) {printf ("[Child thread] destructor excuted, Param = % s \ n", (char *) value );} void * Child1 (void * Arg) {printf ("[Child thread-1] thread enter \ n"); pthread_setspecific (Key, ARG); sleep (2 ); printf ("[Child thread-1] thread returns % s \ n", (char *) pthread_getspecific (key); pthread_exit (null); return NULL ;} void * child2 (void * Arg) {printf ("[Child thread-2] thread enter \ n"); pthread_setspecific (Key, ARG); sleep (1 ); printf ("[Child thread-2] thread returns % s \ n", (char *) pthread_getspecific (key); return NULL ;} static const char * MSG [2] = {"lazy cat", "brown dog"}; int main (INT argc, char * argv []) {printf ("[main thread] Hello \ n"); pthread_key_create (& Key, echomsg); pthread_t tid1, tid2; pthread_create (& tid1, null, Child1, (void *) MSG [0]); pthread_create (& tid2, null, child2, (void *) MSG [1]); pthread_join (tid1, null); pthread_join (tid2, null ); pthread_key_delete (key); printf ("[main thread] exit \ n"); Return 0 ;}
● Create
Int pthread_key_create (pthread_key_t * Key, void (* destructor) (void *))
In Linux, the TSD pool is implemented using a structured array:
Static struct pthread_key_struct pthread_keys [pthread_keys_max] ={{ 0, null }};
Creating a TSD is equivalent to setting an item in the structure array to "in use" state, returning its index to * key, and then setting the destructor function.
We can also see that the maximum number of tsdks is pthread_keys_max. It is defined in/usr/include/bits/local_lim.h, generally 1024.
Do not call the pthread_exit function in destructor.
● Logout
Int pthread_key_delete (pthread_key_t key)
This function does not check whether a thread is using the TSD, nor call the cleaning function (destructor). It only releases the tsd for the next use of pthread_key_create.
In linuxthreads, it also sets the related thread data item to null.
● Read/write
Int pthread_setspecific (pthread_key_t key, const void * value)
Void * pthread_getspecific (pthread_key_t key)