gpt4 book ai didi

C : pthread dataspecific destructor called only once

转载 作者:太空狗 更新时间:2023-10-29 15:39:43 27 4
gpt4 key购买 nike

来自 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 the key, the function pointed to is called with the current 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.

If, after all the destructors have been called for all non-NULL values with associated destructors, there are still some non-NULL values with associated destructors, then the process is repeated. If, after at least [PTHREAD_DESTRUCTOR_ITERATIONS] iterations of destructor calls for out- standing non-NULL values, there are still some non-NULL values with asso- ciated destructors, the implementation stops calling destructors.

我写了一个小例子,其中有一个简单的析构函数,它为一个非 NULL 线程特定值打印“Hello World”。据我所知,这个析构函数只被调用一次(至少在 linux fedora 和 mac os x 上),即使在第一次调用析构函数后线程特定值仍然不是 NULL。

我错过了什么吗?! (PTHREAD_DESTRUCTOR_ITERATIONS = 4 在 glibc 上。)

这是我的小例子:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define NB_THREADS 1
#define NB_KEYS 1

static pthread_key_t keys[NB_KEYS];
static pthread_mutex_t mutex;

void destruction (void *arg)
{
(int) arg ++;
printf ("Destructor called! -- key value : %i\n", (int)arg);
}

void* startup_routine(void* argv)
{
int i;
int th = (int) argv;

for (i = 0; i < NB_KEYS; i++)
pthread_setspecific(keys[i], (void*) ((th + i)* 2));

pthread_mutex_lock(&mutex);

printf("Thread %i\n", th);

for (i = 0; i < NB_KEYS; i++)
printf ("\tkeys[%i] : %i\n", i, (int)pthread_getspecific(keys[i]));

pthread_mutex_unlock(&mutex);

return "End";
}

int main(int argc, char** argv)
{
int i;
void *result;
pthread_t thread[NB_THREADS];

for (i = 0; i < NB_KEYS; i++)
pthread_key_create(&keys[i], destruction);

pthread_mutex_init(&mutex, NULL);

for (i = 0; i < NB_THREADS; i++)
pthread_create( &thread[i], NULL, startup_routine, (void*)(i+1) );

for (i = 0; i < NB_THREADS; i++)
{
pthread_join( thread[i], &result );
printf("Return from the thread %i = '%s'\n", i, (char*)result );
}

return 0;
}

最佳答案

这里好像用pthread的人不多啊!

所以,我再一次回答我自己的问题:

仅当在析构函数中调用 pthread_setspecific 并更改键的值时,析构函数才会被调用多次。

这是因为在调用析构函数之前,key指针被设置为null,并将指针传递给了析构函数。所以如果我们想要key指针不为null,只需要调用其中的pthread_setspecific即可。

关于C : pthread dataspecific destructor called only once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/577133/

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