0

I am reading APUE the chapter about thread specific data. I see following code snipit:

void destructor(void *);
pthread_key_t key;
pthread_once_t init_done = PTHREAD_ONCE_INIT;

void thread_init(void){
    err = pthread_key_create(&key, destructor);
}
int threadfunc(void *arg){
    pthread_once(&init_done, thread_init);
//...
}

I have several questions:

  1. I don't understand how does key initialize
  2. Why does this key need destructor? And what does this destructor do?
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • Possible duplicate of [How do function pointers in C work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – klutt Sep 03 '19 at 15:26
  • `pthread_once` uses a flag to make sure that a function is called one time only. In this case that function is `thread_init`, which uses a pointer to `key` to initialize it, and a pointer to the `destructor` function to clean it up. That is useful to avoid memory leaks or open files or anything that might be opened or allocated because threads can exit for many reasons, such as error conditions. A destructor function makes it easier to handle. – Zan Lynx Sep 03 '19 at 15:46
  • @ZanLynx, but in this example destructor function does nothing. Am I right? – Rudziankoŭ Sep 03 '19 at 15:50
  • 1
    @Rudziankoŭ We don't know because all that code shows is a declaration, not any definition of the function. As is, it would compile but fail to link. – Zan Lynx Sep 03 '19 at 15:53

1 Answers1

3

I don't understand how does key initialize

key is used to identify a slot in thread-specific storage. pthread_key_create stores the slot number in key.

Why does this key need destructor? And what does this destructor do?

See pthread_key_create:

An optional destructor function may be associated with each key value. At thread exit, if a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated with that key, the value of the key is set to NULL, and then the function pointed to is called with the previously associated value as its sole argument. The order of destructor calls is unspecified if more than one destructor exists for a thread when it exits.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271