線程私有數據(TSD)線程中特有的線程存儲, Thread Specific Data 。線程存儲有什么用了?他是什么意思了?大家都知道,在多線程程序中,所有線程共享程序中的變量?,F在有一全局變量,所有線程都可以使用它,改變它的值。 而如果每個線程希望能單獨擁有它,那么就需要使用線程存儲了。表面上看起來這是一個全局變量,所有線程都可以使用它,而它的值在每一個線程中又是單獨存儲 的。這就是線程存儲的意義。 下面說一下線程存儲的具體用法。 l 創(chuàng)建一個類型為 pthread_key_t 類型的變量。 l 調用 pthread_key_create() 來創(chuàng)建該變量。該函數有兩個參數,第一個參數就是上面聲明的 pthread_key_t 變量,第二個參數是一個清理函數,用來在線程釋放該線程存儲的時候被調用。該函數指針可以設成 NULL ,這樣系統(tǒng)將調用默認的清理函數。 l 當線程中需要存儲特殊值的時候,可以調用 pthread_setspcific() 。該函數有兩個參數,第一個為前面聲明的 pthread_key_t 變量,第二個為 void* 變量,這樣你可以存儲任何類型的值。 l 如果需要取出所存儲的值,調用 pthread_getspecific() 。該函數的參數為前面提到的 pthread_key_t 變量,該函數返回 void * 類型的值。 下面是前面提到的函數的原型: 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*)); 下面是一個如何使用線程存儲的例子:
#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; } |
|