pthread_getspecific(key)得到的结果不是NULL,但是没有调用pthread_setspecific(key),为什么?

时间:2015-07-07 13:01:54

标签: c++ linux

.h文件:

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文件

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;
}

为什么if ( client != NULL )在第一次调用此函数时评估为true?我想如果我还没有为当前线程调用pthread_setspecific,那么将从pthread_getspecific返回NULL,因此结果将是false

我错过了什么?

1 个答案:

答案 0 :(得分:1)

在使用该密钥pthread_key_createpthread_getspecific之前,

pthread_setspecific应恰好调用一次。

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

  

pthread_key_create()调用可以在模块初始化例程中明确地进行,也可以通过第一次调用模块[使用pthread_once]隐式完成。