#include<stddef.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#if0//预定义char*str_accumulate(char*s){staticcharaccu[1024]={0};strcat(accu,s);returnaccu;}#endifstaticpthread_key_tstr_key;//顶一个键值staticpthread_once_tstr_alloc_key_once=PTHREAD_ONCE_INIT;//用于解决键冲突staticvoidstr_alloc_key();//按键分配函数staticvoidstr_alloc_destroy_accu(void*accu);//撤销按键分配函数//处理函数char*str_accumulate(constchar*s){char*accu;pthread_once(&str_alloc_key_once,str_alloc_key);//解决按键冲突accu=(char*)pthread_getspecific(str_key);//获取线程的私有数据地址if(accu==NULL){accu=malloc(1024);//分配1024的空间if(accu==NULL)//如果accu为NULL则直接返回NULL{returnNULL;}accu[0]=0;pthread_setspecific(str_key,(void*)accu);//将accu存放的数据作为键值关联printf("Thread%lx:allocatingbufferat%p\n",pthread_self(),accu);//打印输出}strcat(accu,s);//将accu和s字符串连接到一起returnaccu;}//这是一个键值分派函数staticvoidstr_alloc_key(){pthread_key_create(&str_key,str_alloc_destroy_accu);//创建键值printf("Thread%lx:allocatedkey%d\n",pthread_self(),str_key);}//这是撤销键值的函数staticvoidstr_alloc_destroy_accu(void*accu){printf("Thread%lx:freeingbufferat%p\n",pthread_self(),accu);free(accu);//释放空间}//线程处理函数void*threaddeal(void*arg){//该函数的主要工作是将arg的字符串和“Resultof和thread连接到一起”char*str;str=str_accumulate("Resultof");str=str_accumulate((char*)arg);str=str_accumulate("thread");printf("Thread%lx:\"%s\"\n",pthread_self(),str);returnNULL;}//主函数intmain(intargc,char*argv[]){char*str;pthread_tth2,th3;str=str_accumulate("Resultof");pthread_create(&th2,NULL,threaddeal,(void*)"first");pthread_create(&th3,NULL,threaddeal,(void*)"second");//建立两个线程str=str_accumulate("initialthread");printf("Thread%lx:\"%s\"\n",pthread_self(),str);pthread_join(th2,NULL);pthread_join(th3,NULL);//阻塞线程1和线程2return0;}