以示例方式记录pthread_key_t

#include <thread>
#include <iostream>
#include <string>
#include <vector>
#include <chrono>

// 参考链接:https://blog.csdn.net/Kaiwii/article/details/8461277
/*
*   @desc pthread_key_t
*       线程特有变量,对进程来看只有一个变量,但是在线程中,该变量的数据是完全独立的。
*   @method
*       pthread_key_create(&threadData, NULL);
*           作用:创建线程变量
*           参数说明:
*               (1)第一个参数为待创建的pthread_key_t地址
*               (2)第二个参数为线程变量退出的时候调用的清理函数,函数原型为void (void*),其中void行为pthread_key_t中存储的变量
*           注意:特别注意该函数只能在进程中调用一次,不可每个线程都调用。
*       int pthread_setspecific(pthread_key_t key, const void *value);
*            作用:将线程独立变量设置到pthread_key_t类型变量中,注意第二个参数为void*,可以设置任何类型的值
*            参数说明:
*               (1)第一个参数为存储数据的pthread_key_t类型变量
*               (2)第二个参数为待存储的数据的指针,理论上可以存储任何类型的指针
*       void *pthread_getspecific(pthread_key_t key);
*           作用:取出pthread_key_t中存储的变量地址
*           参数说明:
*               (1)第一个参数为待取出来的pthread_key_t类型变量,返回值为其存储的变量指针。
*/
static pthread_key_t threadData;
void ChangeThreadData(int id) {
    // 初始化
    //printf("%lld id:%d\n", std::this_thread::get_id(), id);
    pthread_setspecific(threadData, &id);
    std::this_thread::sleep_for(std::chrono::seconds(3));
    printf("%lld id:%d thread_data:%d\n", std::this_thread::get_id(), id, *((int*)pthread_getspecific(threadData)));    
    // printf("%lld \n", std::this_thread::get_id());    
    // printf("id:%d\n", id); 
    // printf("thread_data:%d\n", *((int*)pthread_getspecific(threadData)));
}

int main() {
    std::vector<std::thread> threadVec;
    // 特别注意pthread_key_t 只能在当前进程初始化的时候create一次,若每个线程中都create一次,会导致程序coredump.
    pthread_key_create(&threadData, NULL);
    for (int i = 0; i < 10; i++)
        threadVec.emplace_back(ChangeThreadData, i);

    for (auto& th : threadVec) {
        th.join();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值