Linux--线程的私有数据如何创建销毁和读取

30 篇文章 7 订阅

线程的私有数据

我们知道,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; 
} 


运行效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值