Can anyone explain me how to use pthread_key_create() , pthread_setspecific(), pthread_getspecific() and pthread_key_delete () routines in pthreads.
Kindly state by an example.
Can anyone explain me how to use pthread_key_create() , pthread_setspecific(), pthread_getspecific() and pthread_key_delete () routines in pthreads.
Kindly state by an example.
pthread_key_create, creates a thread-specific data key.
#include<pthread.h>
int pthread_key_create ( key, destructor )
pthread_key_t * key;
void (*destructor) (void *);
#include <pthread.h>
int pthread_setspecific(pthread_key_t key, const void *value);
The effect of calling pthread_setspecific() with a key value not obtained from pthread_key_create() or after the key has been deleted with pthread_key_delete() is undefined.
#include <pthread.h>
int pthread_key_delete(pthread_key_t key);
pthread_key_delete() can be called from within destructor functions. No destructor functions are invoked by pthread_key_delete(). Any destructor function that may have been associated with the key is no longer called on thread exit.
#include <pthread.h>
void *pthread_getspecific(pthread_key_t key);
Thanks. But all this I have seen in the man pages. Actually I am unable to implement it in a program.
Here's an idea of how I tried to implement the above concepts:
I created a thread key and 2 threads in main and made the main waited untill all the threads were over. In one of the thread ( I assumed that it wil be called first) I binded a value to the key using pthread_setspecific. In the other thread I tried to restore the binded value to the key by calling pthread_getspecific routine. But the value returned by the later is a NULL value.
Kindly direct me as to where I am wrong. Kindly state an example in favour of it's lucid explanation and its implementation techniques.
Well I found out the problem myself. I should have used pthread_getspecific in the same thread instead of the other. But still I have one doubt - In the thread there is a cost overhead of calling set and get specific at intervals. If we declare static array variables of a type ( as many as there are threads ) , perhaps we can achive the same goal.
Is it safe enough to implement the concept in a medium scale project ?