- Linux线程私有数据(Thread-Specific Data,TSD)是指在多线程程序中,每个线程都可以拥有自己的私有数据,这些数据对于其他线程是不可见的。在Linux中,可以使用线程特定数据(Thread-Specific Data,TSD)来实现线程私有数据。
线程特定数据是一种机制,它允许每个线程都拥有自己的私有数据。在Linux中,可以使用pthread_key_create函数创建线程特定数据键,使用pthread_setspecific函数将数据与键关联起来,使用pthread_getspecific函数获取与键关联的数据。
- 类似于errno,不是全局变量,因为多个线程同时访问的话可能出现资源同步问题,私有数据是一键对多值,每个线程可以根据同一个key,设置自己的数据,也可以通过key对数据进行获取
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_key_t key;
struct student{
int id;
char nm[20];
}student_def;
void child1(void* arg)
{
struct student stu_tmp;
memset(&stu_tmp, 0x00, sizeof(student_def));
stu_tmp.id=10;
strcpy(stu_tmp.nm, "hello");
pthread_setspecific(key, (void*)&stu_tmp);
printf("child1:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id,
((struct student*)pthread_getspecific(key))->nm);
}
void child2(void* arg)
{
struct student stu_tmp;
memset(&stu_tmp, 0x00, sizeof(student_def));
stu_tmp.id=20;
strcpy(stu_tmp.nm, "world");
pthread_setspecific(key, (void*)&stu_tmp);
printf("child2:id=%d, nm=%s\n", ((struct student*)pthread_getspecific(key))->id,
((struct student*)pthread_getspecific(key))->nm);
}
int main()
{
pthread_t ptid1;
pthread_t ptid2;
pthread_key_create(&key, NULL);
pthread_create(&ptid1, NULL, (void*)child1, NULL);
pthread_create(&ptid2, NULL, (void*)child2, NULL);
pthread_join(ptid1, NULL);
pthread_join(ptid2, NULL);
pthread_key_delete (key);
return 0;
}