Skip to content
Advertisement

pthread_getspecific(key) get not NULL result, but not call pthread_setspecific(key), why?

.h file :

class RedisThreadLocalClient { 
public: 
    RedisThreadLocalClient() {}
    virtual ~RedisThreadLocalClient(); 
public:
    static void destroy_client(void* client) {
        RedisSyncClient* c = static_cast<RedisSyncClient*>(client);
        delete c;
    }   

    static int init(const std::vector<std::string>& address) {
        _s_address = address;
        return pthread_key_create(&_s_thread_key, RedisThreadLocalClient::destroy_client);  
    }   

   static RedisSyncClient* get_client();

private: 
    static pthread_key_t _s_thread_key;  
    static std::vector<std::string> _s_address; 
}; 

.cc file

pthread_key_t RedisThreadLocalClient::_s_thread_key;
std::vector< std::string> RedisThreadLocalClient::_s_address;

RedisSyncClient* RedisThreadLocalClient::get_client()
{
    RedisSyncClient* client = static_cast<RedisSyncClient*>(pthread_getspecific(_s_thread_key));
    if (client != NULL) // HERE
    {
        return client;
    }

    RedisSyncClient* c = new RedisSyncClient();
    if (c->init(_s_address) != 0)
    {
        delete c;
        return NULL;
    }

    pthread_setspecific(_s_thread_key, c);
    return c;
}

Why is if ( client != NULL ) evaluating as true when first called in this function? I thought if I haven’t-yet called pthread_setspecific for the current thread, NULL would be returned from pthread_getspecific and therefore the result would be false ?

What am I missing?

Advertisement

Answer

pthread_key_create should be called precisely once, before any use of pthread_getspecific or pthread_setspecific with that key.

From http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_key_create.html:

The pthread_key_create() call could either be explicitly made in a module initialization routine, or it can be done implicitly by the first call to a module [using pthread_once].

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement