#include
#include
#include
#include
#include
#if 0 //預(yù)定義
char * str_accumulate(char *s)
{
static char accu[1024]={0};
strcat(accu,s);
return accu;
}
#endif
static pthread_key_t str_key; //頂一個(gè)鍵值
static pthread_once_t str_alloc_key_once = PTHREAD_ONCE_INIT; //用于解決鍵沖突
static void str_alloc_key(); //按鍵分配函數(shù)
static void str_alloc_destroy_accu(void *accu); //撤銷(xiāo)按鍵分配函數(shù)
//處理函數(shù)
char * str_accumulate(const char *s)
{
char *accu;
pthread_once(&str_alloc_key_once,str_alloc_key); //解決按鍵沖突
accu = (char *)pthread_getspecific(str_key); //獲取線(xiàn)程的私有數(shù)據(jù)地址
if(accu == NULL)
{
accu = malloc(1024); //分配1024的空間
if(accu == NULL) //如果accu為NULL則直接返回NULL
{
return NULL;
}
accu[0] = 0;
pthread_setspecific(str_key,(void *)accu); //將accu存放的數(shù)據(jù)作為鍵值關(guān)聯(lián)
printf("Thread %lx : allocating buffer at %p\n",pthread_self(),accu); //打印輸出
}
strcat (accu,s); //將accu和s字符串連接到一起
return accu;
}
//這是一個(gè)鍵值分派函數(shù)
static void str_alloc_key()
{
pthread_key_create(&str_key,str_alloc_destroy_accu); //創(chuàng)建鍵值
printf("Thread %lx : allocated key %d\n",pthread_self(), str_key);
}
//這是撤銷(xiāo)鍵值的函數(shù)
static void str_alloc_destroy_accu(void *accu)
{
printf("Thread %lx : freeing buffer at %p\n",pthread_self(),accu);
free(accu); //釋放空間
}
//線(xiàn)程處理函數(shù)
void *threaddeal(void *arg)
{
//該函數(shù)的主要工作是將arg的字符串和“Result of和thread連接到一起”
char *str;
str = str_accumulate("Result of ");
str = str_accumulate((char *)arg);
str = str_accumulate(" thread");
printf("Thread %lx: \"%s\" \n",pthread_self(),str);
return NULL;
}
//主函數(shù)
int main(int argc, char *argv[])
{
char *str;
pthread_t th2,th3;
str = str_accumulate("Result of ");
pthread_create(&th2,NULL,threaddeal,(void *)"first");
pthread_create(&th3,NULL,threaddeal,(void *)"second"); //建立兩個(gè)線(xiàn)程
str = str_accumulate("initial thread");
printf("Thread %lx :\"%s\"\n",pthread_self(),str);
pthread_join(th2,NULL);
pthread_join(th3,NULL); //阻塞線(xiàn)程1和線(xiàn)程2
return 0;
}
當(dāng)前標(biāo)題:[Linux線(xiàn)程]使用線(xiàn)程的私有數(shù)據(jù)
標(biāo)題網(wǎng)址:
http://weahome.cn/article/pdsdgg.html