获取线程独有数据方法 (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(¤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(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),以后就能获得该值。每个线程都有一份唯一的数据。

你可能感兴趣的:(POSIX,多线程)