• pthread_key_t和pthread_key_create()详解


    下面说一下线程中特有的线程存储, Thread Specific Data 。线程存储有什么用了?他是什么意思了?大家都知道,在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。
    下面说一下线程存储的具体用法。

    1.创建一个类型为pthread_key_t类型的变量。

    2.调用pthread_key_create()来创建该变量。该函数有两个参数,第一个参数就是上面声明的pthread_key_t变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL,这样系统将调用默认的清理函数。该函数成功返回0.其他任何返回值都表示出现了错误。

    3.当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的pthread_key_t变量,第二个为void*变量,这样你可以存储任何类型的值。

    4.如果需要取出所存储的值,调用pthread_getspecific()。该函数的参数为前面提到的pthread_key_t变量,该函数返回void *类型的值。下面是前面提到的函数的原型:

    int pthread_setspecific(pthread_key_t key, const void *value);
    void *pthread_getspecific(pthread_key_t key);
    int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
    
    • 1
    • 2
    • 3

    下面是一个如何使用线程存储的例子:

    #include 
    #include 
    #include 
    #include 
    
    pthread_key_t key; // 好吧,这个玩意究竟是干什么的呢?
    
    struct test_struct { // 用于测试的结构
        int i;
        float k;
    };
    
    void *child1(void *arg)
    {
        struct test_struct struct_data; // 首先构建一个新的结构
        struct_data.i = 10;
        struct_data.k = 3.1415;
        pthread_setspecific(key, &struct_data); // 设置对应的东西吗?
        printf("child1--address of struct_data is --> 0x%p\n", &(struct_data));
        printf("child1--from pthread_getspecific(key) get the pointer and it points to --> 0x%p\n", (struct test_struct *)pthread_getspecific(key));
        printf("child1--from pthread_getspecific(key) get the pointer and print it's content:\nstruct_data.i:%d\nstruct_data.k: %f\n", 
            ((struct test_struct *)pthread_getspecific(key))->i, ((struct test_struct *)pthread_getspecific(key))->k);
        printf("------------------------------------------------------\n");
    }
    void *child2(void *arg)
    {
        int temp = 20;
        sleep(2);
        printf("child2--temp's address is 0x%p\n", &temp);
        pthread_setspecific(key, &temp); // 好吧,原来这个函数这么简单
        printf("child2--from pthread_getspecific(key) get the pointer and it points to --> 0x%p\n", (int *)pthread_getspecific(key));
        printf("child2--from pthread_getspecific(key) get the pointer and print it's content --> temp:%d\n", *((int *)pthread_getspecific(key)));
    }
    int main(void)
    {
        pthread_t tid1, tid2;
        pthread_key_create(&key, NULL); // 这里是构建一个pthread_key_t类型,确实是相当于一个key
        pthread_create(&tid1, NULL, child1, NULL);
        pthread_create(&tid2, NULL, child2, NULL);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
        pthread_key_delete(key);
        return (0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    看一下输出的结果:

    child1--address of struct_data is --> 0x0x7ffff77eff40
    child1--from pthread_getspecific(key) get the pointer and it points to --> 0x0x7ffff77eff40
    child1--from pthread_getspecific(key) get the pointer and print it's content:
    struct_data.i:10
    struct_data.k: 3.141500
    ------------------------------------------------------
    child2--temp's address is 0x0x7ffff6feef44
    child2--from pthread_getspecific(key) get the pointer and it points to --> 0x0x7ffff6feef44
    child2--from pthread_getspecific(key) get the pointer and print it's content --> temp:20
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在安卓的源码/system/core/libutils/Looper.cpp中也可以看到其身影

    sp<Looper> Looper::prepare(int opts) {
        bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
        sp<Looper> looper = Looper::getForThread();//这里获得Looper
        if (looper == nullptr) { //如果是第一次获取Looper,则为空,重新创建一个
            looper = new Looper(allowNonCallbacks);
            Looper::setForThread(looper);//
        }
        if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
            ALOGW("Looper already prepared for this thread with a different value for the "
                    "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
        }
        return looper;
    }
    
    //这里调用pthread_getspecific获得Looper
    sp<Looper> Looper::getForThread() {
        int result = pthread_once(& gTLSOnce, initTLSKey);//这里只会创建一次
        LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
    
        return (Looper*)pthread_getspecific(gTLSKey);
    }
    
    void Looper::initTLSKey() {
        int error = pthread_key_create(&gTLSKey, threadDestructor);//创建gTLSKey
        LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
    }
    
    //将Looper放到gTLSKey中存储起来
    void Looper::setForThread(const sp<Looper>& looper) {
        sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
    
        if (looper != nullptr) {
            looper->incStrong((void*)threadDestructor);
        }
    
        pthread_setspecific(gTLSKey, looper.get());
    
        if (old != nullptr) {
            old->decStrong((void*)threadDestructor);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
  • 相关阅读:
    小白学习MySQL - 增量统计SQL的需求
    离散数学 --- 根树,根数的遍历,最优树和哈夫曼算法
    FastDFS搭建及整合Nginx实现文件上传
    读书笔记:Effective C++ 2.0 版,条款20(避免public出现数据成员)、条款21(尽量用const)
    13数据结构与算法刷题之【动态规划】篇
    1.1 Android 系统概述_智能手机系统介绍
    【Linux】网络带宽计算理论
    linux wc命令
    Spring 远程命令执行漏洞分析(CVE-2022-22965)
    根据前序中序求后序
  • 原文地址:https://blog.csdn.net/qq_34888036/article/details/133960234