Friday, April 26, 2013

pthread_key_delete example c c++


NAME

pthread_key_delete - thread-specific data key deletion

SYNOPSIS

[THR] [Option Start] #include <pthread.h>

int pthread_key_delete(pthread_key_t
 key); [Option End]

DESCRIPTION

The pthread_key_delete() function shall delete a thread-specific data key previously returned by pthread_key_create(). The thread-specific data values associated with key need not be NULL at the time pthread_key_delete() is called. It is the responsibility of the application to free any application storage or perform any cleanup actions for data structures related to the deleted key or associated thread-specific data in any threads; this cleanup can be done either before or after pthread_key_delete() is called. Any attempt to use key following the call to pthread_key_delete() results in undefined behavior.
The pthread_key_delete() function shall be callable from within destructor functions. No destructor functions shall be invoked by pthread_key_delete(). Any destructor function that may have been associated with key shall no longer be called upon thread exit.

RETURN VALUE

If successful, the pthread_key_delete() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_key_delete() function may fail if:
[EINVAL]
The key value is invalid.
The pthread_key_delete() function shall not return an error code of [EINTR].
Example

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.

#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