c – pthread_key_create析构函数未被调用

根据 pthread_key_create手册页,我们可以关联在线程关闭调用的析构函数.我的问题是我注册的析构函数没有被调用.我的代码的要点如下.
static pthread_key_t key;
static pthread_once_t tls_init_flag = PTHREAD_ONCE_INIT;

void destructor(void *t) {
  // thread local data structure clean up code here,which is not getting called
}

void create_key() {
  pthread_key_create(&key,destructor);
}

// This will be called from every thread
void set_thread_specific() {

  ts = new ts_stack; // Thread local data structure

  pthread_once(&tls_init_flag,create_key);
  pthread_setspecific(key,ts);
}

知道什么可能阻止这个析构函数调用?我现在也在使用atexit()来在主线程中进行一些清理.有没有机会干扰析构函数调用?我也尝试删除它.虽然仍然没有奏效.另外我不清楚我是否应该将主线程作为atexit的单独案例处理. (顺便说一下,使用atexit是必须的,因为我需要在应用程序出口处进行一些特定于应用程序的清理)

解决方法

这是设计的.

主线程退出(通过返回或调用exit()),并且不使用pthread_exit(). POSIX文档pthread_exit调用特定于线程的析构函数.

你可以在main的末尾添加pthread_exit().或者,您可以使用atexit进行销毁.在这种情况下,将特定于线程的值设置为NULL将是干净的,因此在调用pthread_exit的情况下,该键的销毁不会发生两次.

更新实际上,我已经通过简单地将其添加到我的全局单元测试设置功能解决了我的直接担忧:

::atexit([] { ::pthread_exit(0); });

所以,在我的全局夹具类MyConfig的上下文中:

struct MyConfig {
    MyConfig()   {
        GOOGLE_PROTOBUF_VERIFY_VERSION;
        ::atexit([] { ::pthread_exit(0); });
    }
    ~MyConfig()  { google::protobuf::ShutdownProtobufLibrary(); }
};

使用的一些参考文献:

> http://www.resolvinghere.com/sof/6357154.shtml
> https://sourceware.org/ml/pthreads-win32/2008/msg00007.html
> http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_key_create.html
> http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_exit.html

PS.当然是c 11 introduced <thread>所以你有更好,更便携的原始人工作.

相关文章

对象的传值与返回说起函数,就不免要谈谈函数的参数和返回值...
从实现装饰者模式中思考C++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...