Thread-Specific Data(TSD)线程私有数据

一句话总结:线程共享一个全局变量key,但对应的value每个线程都有一份,互不影响。


表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的,这就是线程存储的意义。
1、首先需要创建一个类型为pthread_key_t类型的变量。
2、调用pthread_key_create()来创建该变量。该函数有两个参数,第一个参数就是上面声明的pthread_key_t变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL,这样系统将调用默认的清理函数。该函数成功返回0.其他任何返回值都表示出现了错误。

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

int pthread_setspecific(pthread_key_t key, const void *value);
4、如果需要取出所存储的值,调用pthread_getspecific()。该函数的参数为前面提到的pthread_key_t变量,该函数返回void *类型的值。

void *pthread_getspecific(pthread_key_t key);



#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <pthread.h>

#include <string>


pthread_key_t key;


class CTest

{

public:

    CTest(int m_, int n_):m(m_), n(n_){};

    ~CTest(){};

    int m;

    int n;

};


void *child1(void *arg)

{

    CTest ctest(10, 20);

    pthread_setspecific(key, &ctest); // 设置对应value,可是任何类型

    printf("key: %ld\n", key);

    printf("child1--address of class is --> %p\n", &ctest); //%p输出指针类型,16进制,前面附加0x

    printf("child1--from pthread_getspecific(key) get the pointer: %p\n", (CTest *)pthread_getspecific(key));

    printf("child1--print value:\nm: %d\nn: %d\n",

           ((CTest *)pthread_getspecific(key))->m, ((CTest *)pthread_getspecific(key))->n);

    return NULL;

}


void *child2(void *arg)

{

    std::string str("I am thread2");

    sleep(2);   //等待Thread1 运行完

    printf("child2--str address is %p\n", &str);

    pthread_setspecific(key, &str);

    printf("key: %ld\n", key);

    printf("child2--from pthread_getspecific(key) get the pointer: %p\n", (int *)pthread_getspecific(key));

    printf("child2--print value --> str:%s\n", (char*)pthread_getspecific(key));

    return NULL;

}


int main(void)

{

    pthread_t tid1, tid2;

    pthread_key_create(&key, NULL); //创建一个key

    printf("key: %ld\n", 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);    //删除key

    return (0);

}


运行结果:

key: 258

key: 258

child1--address of class is --> 0x700000080ee0

child1--from pthread_getspecific(key) get the pointer: 0x700000080ee0

child1--print value:

m: 10

n: 20

child2--str address is 0x700000103e90

key: 258

child2--from pthread_getspecific(key) get the pointer: 0x700000103e90

child2--print value --> str:I am thread2

Program ended with exit code: 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值