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(¤t_thread_data_key, destroy_current_thread_data);
}
static void *get_thread_data()
{
printf("func: %s\n", __FUNCTION__);
pthread_once(¤t_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(¤t_thread_data_once, create_current_thread_data_key);
pthread_setspecific(current_thread_data_key, data);
}
用法:
在每個線程獲取值(get_thread_data),如果爲空,先設置一個值(set_thread_data),以後就能獲得該值。每個線程都有一份唯一的數據。