版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CeeLo_Atom/article/details/48549177
线程私有数据(也称线程特有数据)是存储和查询与某个线程相关的数据的一种机制。把这种数据称为线程私有数据或特定数据的原因是,希望每个线程可以独立地访问数据副本,而不需要担心与其他线程的同步访问问题。
#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;
}