?
在單線程程序中,經常要用全局變量實現共享數據。在多線程環境下,由于數據空間是共享的,因此全局變量也是各線程共有。但有時在應用程序設計過程中有必要
提供線程私有的全局變量,僅在某個線程中有效,卻可以跨多個函數進行訪問,比如程序可能需要每個線程維護一個鏈表,要使用相同的函數操作,最簡單的辦法就
是使用同名而不同變量地址的線程相關數據結構。這樣的數據結構就是私有數據(TSD)
???
??? 程序就是演示這樣的數據結構。創建了兩個新的線程,分別把自己的ID寫入私有數據,然后互不干擾的輸出。代碼如下:
#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;
}