C:pthread数据特定的析构函数只调用一次

C:pthread数据特定的析构函数只调用一次,第1张

概述从 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 as 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.

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

我错过了什么吗?! (glibc上的PTHREAD_DESTRUCTOR_IteraTIONS = 4.)

这是我的小例子:

#include <pthread.h>#include <stdio.h>#include <stdlib.h>#define NB_THREADS 1#define NB_KEYS 1static 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",(char*)result );  }  return 0;}
解决方法 似乎在这里没有很多人使用pthread!

那么,我将再次回答我自己的问题:

只有在析构函数中调用pthread_setspecific时,才会多次调用析构函数,从而更改键的值.

这是因为在调用析构函数之前,键指针设置为null并且指针被传递给析构函数.因此,如果我们希望键指针不为null,只需要在其中调用pthread_setspecific.

总结

以上是内存溢出为你收集整理的C:pthread数据特定的析构函数只调用一次全部内容,希望文章能够帮你解决C:pthread数据特定的析构函数只调用一次所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1229403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存