- 类似于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;
}