Pthread thread-local-singleton when to release a tls key?

I implemented a kind of "streaming local singleton" using pthread TLS, and I wondered how (and when) I could remove pthread_key_t in this case, because, as now, the memory used by the TLS key will never be free.

The alleged use of this is to allow class A to get from ThreadLocalSingleton <A> which makes A thread a local singleton, assuming A has only private constructors and ThreadLocalSingleton <A> is a friend of A.

Oh, and also - you see any problems with this implementation; I did not notice anything important?

#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;
+5
source share
1 answer

.

pthread_key_create, NULL :

. , -NULL, , NULL, , NULL, .

, , pthread. , , delete ((T*)obj);.

+2

All Articles