线程的私有数据
原创
©著作权归作者所有:来自51CTO博客作者wx6405b2c488d4e的原创作品,请联系作者获取转载授权,否则将追究法律责任
/*
* main.cpp
*
* Created on: Jun 27, 2014
* Author: john
*/
#include<string.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
pthread_key_t key;
void* thread_1(void* arg)
{
int tsd=5;
printf("thread1 %u is running\n",pthread_self());
pthread_setspecific(key,(void*)&tsd);
printf("thread1 %u ",pthread_self());
int* a=(int*)pthread_getspecific(key);
printf("return %d\n",*a);
}
void* thread_2(void* arg)
{
int tsd=0;
pthread_t thid2;
printf("thread2 %u is running\n",pthread_self()) ;
pthread_setspecific(key,(void*)&tsd);
pthread_create(&thid2,NULL,thread_1,NULL);
sleep(5);
printf("thread2 %u ",pthread_self());
int* a=(int*)pthread_getspecific(key);
printf("return %d\n",*a);
}
int main()
{
pthread_t thid1;
printf("main thread %u is running \n",pthread_self());
pthread_key_create(&key,NULL);
int tsd=0;
pthread_setspecific(key,(void*)&tsd);
pthread_create(&thid1,NULL,thread_2,NULL);
sleep(10);
pthread_key_delete(key);
printf("main thread exit\n");
}
现在呢,说说,线程的私有数据是采用了一种被称为一键多值的技术,一个键值对应多个数值,访问数据时都是通过键值来访问,好像是对一个变量进行访问,其实是在访问不同的数据,使用线程私有数据的时候首先要为每个线程创建一个相关联的键
这里面用到几个API
#include<pthread.h>
int pthread_key_create(pthread_key_t *key,void(*destr_function)(void*));//创建线程的私有变量
int pthread_setspecific(pthread_key_t key,const void* pointer);//设置线程私有变量的值
void* pthread_getspecific(pthread_key_t key);//获取线程私有变量的值
int pthread_key_delete(pthread_key_t key);//删除线程的私有变量