?
在單線程程序中,經(jīng)常要用全局變量實(shí)現(xiàn)共享數(shù)據(jù)。在多線程環(huán)境下,由于數(shù)據(jù)空間是共享的,因此全局變量也是各線程共有。但有時(shí)在應(yīng)用程序設(shè)計(jì)過(guò)程中有必要
提供線程私有的全局變量,僅在某個(gè)線程中有效,卻可以跨多個(gè)函數(shù)進(jìn)行訪問(wèn),比如程序可能需要每個(gè)線程維護(hù)一個(gè)鏈表,要使用相同的函數(shù)操作,最簡(jiǎn)單的辦法就
是使用同名而不同變量地址的線程相關(guān)數(shù)據(jù)結(jié)構(gòu)。這樣的數(shù)據(jù)結(jié)構(gòu)就是私有數(shù)據(jù)(TSD)
???
??? 程序就是演示這樣的數(shù)據(jù)結(jié)構(gòu)。創(chuàng)建了兩個(gè)新的線程,分別把自己的ID寫(xiě)入私有數(shù)據(jù),然后互不干擾的輸出。代碼如下:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
?
pthread_key_t key;
?
void echomsg(int t)
{
?printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);???
?
}
void child()
{
?int tid;
?
?tid = pthread_self();?
?? printf("thread %d enter\n",tid);
?sleep(1);
?? pthread_setspecific(key,(void *)tid);
?? printf("thread %d returns %d\n",tid,pthread_getspecific(key));
?sleep(1);
}
int main()
{
?pthread_t tid1,tid2;
?
?? printf("Hello\n");
??
?? pthread_key_create(&key,(void *)echomsg);?? pthread_create(&tid1,NULL,(void *)child,NULL);
?? pthread_create(&tid2,NULL,(void *)child,NULL);
??
?? pthread_join(tid1,NULL);
?pthread_join(tid2,NULL);
?? pthread_key_delete(key);??
?? printf("main thread exit\n");??
?? return 0;
}