獲取線程獨有數據方法 (POSIX標準方法)

static pthread_once_t current_thread_data_once = PTHREAD_ONCE_INIT;
static pthread_key_t current_thread_data_key;

 
static void destroy_current_thread_data(void *p)
{
    printf("func: %s\n", __FUNCTION__);
}

 
static void create_current_thread_data_key()
{
    printf("func: %s\n", __FUNCTION__);
    pthread_key_create(&current_thread_data_key, destroy_current_thread_data);
}

 
static void *get_thread_data()
{
    printf("func: %s\n", __FUNCTION__);

 
    pthread_once(&current_thread_data_once, create_current_thread_data_key);
    return reinterpret_cast<void *>(pthread_getspecific(current_thread_data_key));
}

 
static void set_thread_data(void *data)
{
    printf("func: %s\n", __FUNCTION__);

 
    pthread_once(&current_thread_data_once, create_current_thread_data_key);
    pthread_setspecific(current_thread_data_key, data);
}

 

用法:

在每個線程獲取值(get_thread_data),如果爲空,先設置一個值(set_thread_data),以後就能獲得該值。每個線程都有一份唯一的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章