Linux--线程的私有数据如何创建销毁和读取
线程的私有数据
我们知道,Linux中多线程之间是共享内存的,那么一个全局变量更改了会影响别的线程,那么如何定义线程自己的私有数据呢?
TSD私有数据,同名但是不同内存地址的私有数据结构
私有数据的创建销毁以及读取
函数 | 描述 |
---|---|
int pthread_key_create(pthread_key_t *key, void (destructor)(void)) | 私有数据的创建 |
int pthread_key_delete(pthread_key_t key) | 私有数据的销毁 |
void *pthread_getspecific(pthread_key_t key) | 私有数据的读取 |
int pthread_setspecific(pthread_key_t key, const void *value) | 私有数据的写入 |
私有数据的定义
pthread_key_t key;
pthread_key_create参数:
pthread_key_t *key:定义的私有数据的地址
void (destructor)(void): 私有数据的回调函数(销毁的时候调用)
int pthread_key_delete参数:
pthread_key_t key:私有数据
void *pthread_getspecific参数
pthread_key_t key:私有数据
pthread_setspecific参数:
pthread_key_t key:私有数据
const void *value:要写入私有数据的值的地址
demo
//this is the test code for pthread_key
#include <stdio.h>
#include <pthread.h>
pthread_key_t key;
void echomsg(void *t) //私有数据的回调函数
{
printf("destructor excuted in thread %u,param=%u\n",pthread_self(),((int *)t));
}
void * child1(void *arg) //线程1的执行函数
{
int i=10;
int tid=pthread_self();
printf("\nset key value %d in thread %u\n",i,tid);
pthread_setspecific(key,&i);
printf("thread one sleep 2 until thread two finish\n");
sleep(2);
printf("\nthread %u returns %d,add is %u\n",tid,*((int *)pthread_getspecific(key)),(int *)pthread_getspecific(key));
}
void * child2(void *arg) //线程2的执行函数
{
int temp=20;
int tid=pthread_self();
printf("\nset key value %d in thread %u\n",temp,tid);
pthread_setspecific(key,&temp);
sleep(1);
printf("thread %u returns %d,add is %u\n",tid,*((int *)pthread_getspecific(key)),(int *)pthread_getspecific(key));
}
int main(void)
{
pthread_t tid1,tid2; //创建两个线程的ID
pthread_key_create(&key,echomsg); //创建私有数据
pthread_create(&tid1,NULL,(void *)child1,NULL); //创建线程1
pthread_create(&tid2,NULL,(void *)child2,NULL); //创建线程2
pthread_join(tid1,NULL); //主线程等待线程1结束
pthread_join(tid2,NULL); //主线程等待线程2结束
pthread_key_delete(key); //销毁私有数据
return 0;
}