ptg10805159
448 Thread Control Chapter 12
#include <pthread.h>
int pthread_key_delete(pthread_key_tkey);
Returns: 0 if OK, error number on failure
Note that calling pthread_key_delete will not invoke the destructor function
associated with the key.Tofreeany memory associated with the key’s thread-specific
data values, we need to take additional steps in the application.
We need to ensurethat a key we allocate doesn’t change because of a race during
initialization. Code like the following can result in two threads both calling
pthread_key_create:
void destructor(void *);
pthread_key_t key;
int init_done = 0;
int
threadfunc(void *arg)
{
if (!init_done) {
init_done = 1;
err = pthread_key_create(&key, destructor);
}
..
.
}
Depending on how the system schedules threads, some threads might see one key
value, whereas other threads might see a different value. The way to solve this race is
to usepthread_once.
#include <pthread.h>
pthread_once_tinitflag=PTHREAD_ONCE_INIT;
int pthread_once(pthread_once_t *initflag,void (*initfn)(void));
Returns: 0 if OK, error number on failure
The initflag must be a nonlocal variable (i.e., global or static) and initialized to
PTHREAD_ONCE_INIT.
If each thread callspthread_once,the system guarantees that the initialization
routine,initfn,will be called only once, on the first call topthread_once.The proper
way to create a key without a race is as follows:
void destructor(void *);
pthread_key_t key;
pthread_once_t init_done = PTHREAD_ONCE_INIT;