c++ - pthread_key_create 析构函数未被调用

标签 c++ pthreads shutdown thread-specific-storage

根据 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调用线程特定的析构函数。

您可以添加 pthread_exit()main 的末尾.或者,您可以使用 atexit做你的破坏。在这种情况下,将特定于线程的值设置为 NULL 会很干净。所以如果pthread_exit被调用时,该 key 的销毁不会发生两次。

更新 实际上,我已经通过简单地将它添加到我的全局单元测试设置函数中解决了我眼前的担忧:

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

因此,在我的全局夹具类的上下文中 MyConfig :

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

使用的一些引用资料:


附言。当然是 c++11 introduced <thread> 因此您可以使用更好、更便携的原语。

关于c++ - pthread_key_create 析构函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521968/

相关文章:

c++ - 是否有安全/标准的方法来管理 C++ 中的非结构化内存?

C++ 结构无效使用非静态数据成员

c++ - ios_base 和静态成员

c - pthread 条件循环

c - systemd 如何向服务发送消息以引发 sd_notify(3) 响应?

c++ - 检测模板化 operator() 的限定符

c - 奇怪的 printf/pthread 错误?

java - 即使用户关闭应用程序后,是否可以让倒计时器继续运行

redis - 由于 Redis,我的计算机没有关闭

c++ - 接收比发送的 C++ 更多的字节