linux多執行緒之 執行緒資料TSD Thread Specific Data
阿新 • • 發佈:2018-12-01
在linux中,同一程序下所有執行緒是共享全域性變數的,但有時候會有這樣的需求,某一個執行緒想單獨用於某個全域性變數。這就有了TSD,Thread Specific Data。
使用TSD時需要建立一個全域性的鍵值,每個執行緒都通過鍵值來設定和獲取自己所獨有的全域性變數。
使用TSD分為以下幾個步驟
1、建立一個鍵值,key為一個鍵值,destructor是一個destructor函式,
如果這個引數不為空,那麼當每個執行緒結束時,系統將呼叫這個函式來釋放繫結在這個鍵上的記憶體塊
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
2、通過鍵值設定執行緒私有資料,key為鍵值,pointer是私有資料的地址,該函式將私有資料的地址告訴鍵值key
int pthread_setspecific(pthread_key_t key,const void *pointer));
3、通過鍵值獲取私有資料
void *pthread_getspecific(pthread_key_t key);
4、銷燬鍵值,鍵值使用完畢將鍵值銷燬釋放
pthread_key_delete(pthread_key_t key);
簡單的測試程式碼
#include <pthread.h> #include <stdio.h> pthread_key_t key; pthread_t thid1; pthread_t thid2; void* thread2(void* arg) { printf("thread:%lu is running\n", pthread_self()); int key_va = 20 ; pthread_setspecific(key, (void*)key_va); printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key)); } void* thread1(void* arg) { printf("thread:%lu is running\n", pthread_self()); int key_va = 10; pthread_setspecific(key, (void*)key_va); printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key)); } int main() { pthread_key_create(&key, NULL); pthread_create(&thid1, NULL, thread1, NULL); pthread_create(&thid2, NULL, thread2, NULL); pthread_join(thid1, NULL); pthread_join(thid2, NULL); pthread_key_delete(key); return 0; }
執行結果