Thread-Specific Data(线程私有数据)

       线程私有数据(也称线程特有数据)是存储和查询与某个线程相关的数据的一种机制。把这种数据称为线程私有数据或特定数据的原因是,希望每个线程可以独立地访问数据副本,而不需要担心与其他线程的同步访问问题。




#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

pthread_key_t key_handle;

typedef struct tag_tsd_data
{
	int iData;
	//TODO
}STD_DATA;

void destructor()
{
	printf("pthread_key destructor.\n");
}

int tsd_key_init()
{
	int iRet = 0;
	iRet = pthread_key_create(&key_handle, destructor);
	if(iRet != 0)
	{
		printf("pthread_key_create error.\n");
	}
	return iRet;
}

STD_DATA* get_thread_std()
{
	STD_DATA* pStd = NULL;
	pStd = pthread_getspecific(key_handle);
	if(pStd == NULL)
	{
		pStd = (STD_DATA*)malloc(sizeof(STD_DATA));
		if(pStd == NULL)
		{
			printf("malloc error.\n");
			return NULL;
		}
		memset(pStd, 0, sizeof(STD_DATA));
		pthread_setspecific(key_handle, pStd);
	}
	return pStd;
}

void *thread_fun2(void *arg)
{
	STD_DATA *pStd = NULL;
	printf("thread [%d] is running...\n", (int)pthread_self());

	pStd = get_thread_std();
	if(pStd == NULL)
	{
		printf("fun1 get std error.\n");
		return NULL;
	}
	pStd->iData = (int)pthread_self();
	printf("fun 2 thread [%d], thread specific data [%d].\n", (int)pthread_self(), pStd->iData);
	return NULL;
}

void* thread_fun1(void *arg)
{
	pthread_t tid;
	STD_DATA *pStd = NULL;
	printf("thread [%d] is running...\n", (int)pthread_self());
	pthread_create(&tid, NULL, thread_fun2, 0);

	pStd = get_thread_std();
	if(pStd == NULL)
	{
		printf("fun1 get std error.\n");
		return NULL;
	}
	pStd->iData = (int)pthread_self();
	printf("fun 1 thread [%d], thread specific data [%d].\n", (int)pthread_self(), pStd->iData);
	sleep(3);
	return NULL;
}

int main(int argc, char *argv[])
{
	pthread_t tid;
	int iRet = -1;

	iRet = tsd_key_init();
	if(iRet)
	{
		printf("init tsd key error.\n");
		return 0;
	}
	STD_DATA* pStd = NULL;
	pStd = get_thread_std();

	if(pStd == NULL)
	{
		printf("get specific std error.\n");
		return 0;
	}
	pStd->iData = (int)pthread_self();

	printf("main thread [%d], thread specific data [%d].\n", (int)pthread_self(), pStd->iData);

	iRet = pthread_create(&tid, NULL, thread_fun1, 0);
	if(iRet != 0)
	{
		printf("pthread_create error.\n");
		return 0;
	}

	sleep(5);
        pthread_key_delete(key_handle);
	return 0;
}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值