線程私有數(shù)據(jù)(TSD)線程中特有的線程存儲(chǔ), Thread Specific Data 。線程存儲(chǔ)有什么用了?他是什么意思了?大家都知道,在多線程程序中,所有線程共享程序中的變量?,F(xiàn)在有一全局變量,所有線程都可以使用它,改變它的值。 而如果每個(gè)線程希望能單獨(dú)擁有它,那么就需要使用線程存儲(chǔ)了。表面上看起來(lái)這是一個(gè)全局變量,所有線程都可以使用它,而它的值在每一個(gè)線程中又是單獨(dú)存儲(chǔ) 的。這就是線程存儲(chǔ)的意義。 下面說(shuō)一下線程存儲(chǔ)的具體用法。 l 創(chuàng)建一個(gè)類型為 pthread_key_t 類型的變量。 l 調(diào)用 pthread_key_create() 來(lái)創(chuàng)建該變量。該函數(shù)有兩個(gè)參數(shù),第一個(gè)參數(shù)就是上面聲明的 pthread_key_t 變量,第二個(gè)參數(shù)是一個(gè)清理函數(shù),用來(lái)在線程釋放該線程存儲(chǔ)的時(shí)候被調(diào)用。該函數(shù)指針可以設(shè)成 NULL ,這樣系統(tǒng)將調(diào)用默認(rèn)的清理函數(shù)。 l 當(dāng)線程中需要存儲(chǔ)特殊值的時(shí)候,可以調(diào)用 pthread_setspcific() 。該函數(shù)有兩個(gè)參數(shù),第一個(gè)為前面聲明的 pthread_key_t 變量,第二個(gè)為 void* 變量,這樣你可以存儲(chǔ)任何類型的值。 l 如果需要取出所存儲(chǔ)的值,調(diào)用 pthread_getspecific() 。該函數(shù)的參數(shù)為前面提到的 pthread_key_t 變量,該函數(shù)返回 void * 類型的值。 下面是前面提到的函數(shù)的原型: int pthread_setspecific(pthread_key_t key, const void *value); void *pthread_getspecific(pthread_key_t key); int pthread_key_create(pthread_key_t *key, void (*destructor)(void*)); 下面是一個(gè)如何使用線程存儲(chǔ)的例子:
#include <stdio.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 * child1(void *arg) { int tid=pthread_self(); printf("thread %d enter\n",tid); pthread_setspecific(key,(void *)tid); sleep(2); printf("thread %d returns %d\n",tid,pthread_getspecific(key)); sleep(5); } void * child2(void *arg) { int tid=pthread_self(); printf("thread %d enter\n",tid); pthread_setspecific(key,(void *)tid); sleep(1); printf("thread %d returns %d\n",tid,pthread_getspecific(key)); sleep(5); } int main(void) { int tid1,tid2; printf("hello\n"); pthread_key_create(&key,echomsg); pthread_create(&tid1,NULL,child1,NULL); pthread_create(&tid2,NULL,child2,NULL); sleep(10); pthread_key_delete(key); printf("main thread exit\n"); return 0; } |
|