新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
[Linux線程]使用線程的私有數(shù)據(jù)-創(chuàng)新互聯(lián)
#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); //撤銷按鍵分配函數(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); //獲取線程的私有數(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); } //這是撤銷鍵值的函數(shù) static void str_alloc_destroy_accu(void *accu) { printf("Thread %lx : freeing buffer at %p\n",pthread_self(),accu); free(accu); //釋放空間 } //線程處理函數(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è)線程 str = str_accumulate("initial thread"); printf("Thread %lx :\"%s\"\n",pthread_self(),str); pthread_join(th2,NULL); pthread_join(th3,NULL); //阻塞線程1和線程2 return 0; }

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
分享文章:[Linux線程]使用線程的私有數(shù)據(jù)-創(chuàng)新互聯(lián)
分享URL:http://www.dlmjj.cn/article/dhpssj.html


咨詢
建站咨詢
