本文将描述線程的一個比較重要的一方面:線程私有資料,如下代碼:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
pthread_key_t kKey = 0;
void * ThreadProc(void* arg)
{
char* a = (char*)(arg);
sleep(2);
pthread_setspecific(kKey, a);
sleep(1);
char* str = (char*)pthread_getspecific(kKey);
printf("thread: %s/n", str);
}
int main()
{
pthread_t thread_handle1 = 0;
pthread_t thread_handle2 = 0;
char a[] = {"i am A"};
char b[] = {"i am B"};
pthread_create(&thread_handle1, NULL, ThreadProc, a);
pthread_key_create(&kKey, NULL);
pthread_create(&thread_handle2, NULL, ThreadProc, b);
void* out1 = NULL;
void* out2 = NULL;
pthread_join(thread_handle1, &out1);
pthread_join(thread_handle2, &out2);
return 0;
}
使用線程私有資料的步驟:
1)使用pthread_key_create配置設定一個線程私有資料的key,這裡需要注意的是當我們調用了這個函數
之後程序中所有的線程都可以使用這個key,并且通過這個key擷取到的私有資料是互不相同的,比如線程
A通過key設定了資料D,但線程B并沒有設定資料,那麼A通過key擷取的資料當然是D,而B擷取的是一個
空的值。另外需要注意的是不管線程是在pthread_key_create調用之前或之後産生,它都能夠在函數調用
之後使用這個key。
2)使用pthread_setspecific函數将key和一個線程私有資料綁定。
3)通過pthread_getspecific函數和key擷取到這個線程的私有資料。
我一直覺得線程私有資料政策很好用,但考慮到使用過程中需要進行“系統調用”(pthread_getspecific是系統調用嗎?),
如果比較頻繁地調用這個函數的話說不定會使程式的性能下降,但看了man文檔中的一句話後這個中顧慮稍微減輕,盡管還是有疑問:
“the function to pthread_getspecific() has been designed to favor speed and simplicity over error reporting”
上面說它的速度已經被設計地很快了。