我使用 pthread TLS 实现了一种“线程本地单例”,我想知道在这种情况下我如何(以及何时)可以删除 pthread_key_t,因为就像现在一样,TLS 密钥使用的内存永远不会空闲' d。
其预期用途是让类 A 从 ThreadLocalSingleton<A> 派生,这使 A 成为线程本地单例,假设 A 只有私有构造函数并且 ThreadLocalSingleton<A> 是 A 的朋友。
哦,还有 - 你看到那个实现有什么问题吗?我忽略了什么重要的事情吗?
#include <pthread.h>
#include <iostream>
template <class T>
class ThreadLocalSingleton
{
private:
static pthread_key_t tlsKey;
static pthread_once_t tlsKey_once;
static void tls_make_key()
{
(void)pthread_key_create(&ThreadLocalSingleton::tlsKey, ThreadLocalSingleton::tls_destructor);
}
static void tls_destructor(void* obj)
{
delete ((T*)obj);
pthread_setspecific(tlsKey, NULL); // necessary or it will call the destructor again.
}
public:
/*
* A thread-local singleton getter, the resulted object must never be released,
* it is auto-released when the thread exits.
*/
static T* getThreadInstance(void)
{
pthread_once(&tlsKey_once, ThreadLocalSingleton::tls_make_key);
T* instance = (T*)pthread_getspecific(tlsKey);
if(!instance)
{
try
{
instance = new T;
pthread_setspecific(tlsKey, instance);
}
catch (const char* ex)
{
printf("Exception during thread local singleton init: %s\n",ex);
}
}
return instance;
}
};
template <class T>
pthread_key_t ThreadLocalSingleton<T>::tlsKey;
template <class T>
pthread_once_t ThreadLocalSingleton<T>::tlsKey_once = PTHREAD_ONCE_INIT;