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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值