gpt4 book ai didi

c - 为什么 pthread_key 需要析构函数?

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:13 24 4
gpt4 key购买 nike

我正在阅读 APUE关于线程特定数据的章节。我看到以下代码片段:

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);
//...
}

我有几个问题:

  1. 我不明白key是如何初始化的
  2. 为什么这个键需要析构函数?这个析构函数是做什么的?

最佳答案

I don't understand how does key initialize

key 用于标识线程特定存储中的槽。 pthread_key_create 将槽号存储在key中。

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

参见 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.

关于c - 为什么 pthread_key 需要析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57774613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com