根据 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(); }
};
使用的一些引用资料:
- 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
附言。当然是 c++11 introduced <thread>
因此您可以使用更好、更便携的原语。
关于c++ - pthread_key_create 析构函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521968/