|
Syntax #include <pthread.h> int pthread_key_create(pthread_key_t *key, void (*destructor)(void *)); Threadsafe: Yes Signal Safe: No |
The pthread_key_create() function creates a thread local storage key for the process and associates the destructor function with that key. After a key is created, that key can be used to set and get per thread data pointer. When pthread_key_create() completes, the value associated with the newly created key is NULL.
When a thread terminates, if both the value and the destructor associated with a thread local storage key are non NULL, the destructor function will be called. The parameter passed to the destructor function when it is called is the value of the pointer associated with that key in the thread that is terminating.
After calling the destructors, if there are still non NULL values in the thread associated with the keys, the process is repeated. After PTHREAD_DESTRUCTOR_ITERATIONS attempts to destroy the thread local storage, no further attempts will be made for that thread local storage value/key combination.
Do not call pthread_exit() from a destructor function.
A destructor function is not called as a result of the application calling pthread_key_delete().
None.
If pthread_key_create() was not successful, the error condition returned usually indicates one of the following errors. Under some conditions, the value returned could indicate an error other than those listed here.
#define _MULTI_THREADED
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include "check.h"
pthread_key_t tlsKey = 0;
void globalDestructor(void *value)
{
printf("In the data destructor\n");
free(value);
pthread_setspecific(tlsKey, NULL);
}
int main(int argc, char **argv)
{
int rc=0;
int i=0;
printf("Enter Testcase - %s\n", argv[0]);
printf("Create a thread local storage key\n");
rc = pthread_key_create(&tlsKey, globalDestructor);
checkResults("pthread_key_create()\n", rc);
/* The key can now be used from all threads */
printf("- The key can now be used from all threads\n");
printf("- in the process to storage thread local\n");
printf("- (but global to all functions in that thread)\n");
printf("- storage\n");
printf("Delete a thread local storage key\n");
rc = pthread_key_delete(tlsKey);
checkResults("pthread_key_delete()\n", rc);
/* The key and any remaining values are now gone. */
printf("Main completed\n");
return 0;
}
Output
Enter Testcase - QP0WTEST/TPKEYC0 Create a thread local storage key - The key can now be used from all threads - in the process to storage thread local - (but global to all functions in that thread) - storage Delete a thread local storage key Main completed