#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
pthread_key_t key;
void *thread1(void *arg)
{
int i=10;
int tid=pthread_self();
printf("In thread 1,ID :%u\n",tid);
printf("Set the private value1\n");
pthread_setspecific(key,&i);
sleep(2); //等待线程2改变数据,看是否有影响
printf("The value in thread1 is %d\n",(*(int *)pthread_getspecific(key)));
}
void *thread2(void *arg)
{
int j=20;
int tid=pthread_self();
printf("In thread 2,ID :%u\n",tid);
printf("Set the private value2\n");
pthread_setspecific(key,&j);
sleep(1);
printf("The value in thread2 is %d\n",(*(int *)pthread_getspecific(key)));
}
int main(void)
{
pthread_t td1,td2;
pthread_key_create(&key,NULL);
pthread_create(&td1,NULL,(void *)thread1,NULL);
pthread_create(&td2,NULL,(void *)thread2,NULL);
pthread_join(td1,NULL); //等待子线程结束
pthread_join(td2,NULL); //等待子线程结束
pthread_key_delete(key);
return 0;
}
运行结果:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。