线程特定数据函数的使用

《APUE》 12.6节


线程特定数据(或线程私有数据,TSD)  的学习


建议参考《unix网络编程卷1》的第26.5节来看,它讲得更加详细。


练习代码如下:

#include "apue.h"
#include <pthread.h>

static pthread_key_t r_key;
static pthread_once_t  r_once = PTHREAD_ONCE_INIT;


void  free_buf(void * buf)
{
	free(buf);
}


void key_init(void)
{
	pthread_key_create(&r_key,free_buf);
}

void * operation(void * thread_num)
{
	int  num = (int)thread_num;
	pthread_detach(pthread_self());
	pthread_once(&r_once,key_init);
	int * data;
	
	if(pthread_getspecific(r_key) == NULL)
	{
		printf("malloc:\n");
		data = (int *)malloc(sizeof(int));
		pthread_setspecific(r_key,data);
		*data = num;
	}


	printf("the specific data of Thread %d is %d\n",num, *((int *)pthread_getspecific(r_key)));
	

	if(num == 1234)
	{
		sleep(5);// 让5678进程能够执行到sleep 10s
		pthread_key_delete(r_key);
	}else
	{   // 让1234进程能够执行到sleep 5,delete key
		sleep(10);
	}

	if(pthread_getspecific(r_key) != NULL)
	{
		printf("-----the specific data of Thread %d is %d\n",num, 
			*((int *)pthread_getspecific(r_key)));
	}else
	{
		printf("---- the Thread num is %d, and it  have no specific data \n",num);
	}


	pthread_exit(NULL);
	
	return((void *)0);
}

int main()
{

	pthread_t tid1,tid2;
	int err = 0;

	err = pthread_create(&tid1,NULL,operation,(void *)1234);
	if(err != 0)
	{
		printf("can not crate thread 1\n");
		return -1;
	}

	err = pthread_create(&tid2,NULL,operation,(void *)5678);
	if(err != 0)
	{
		printf("can not crate thread 2\n");
		return -1;
	}


	sleep(20);//等待线程打印结果
	
	return 0;
	
}



可以看到在thread 1234执行了pthread_key_delete()之后,不仅切断了thread 1234与其线程特定数据之间的联系,而且也切断了thread 5678与其线程特定数据之间的联系。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值