linux下的線程真是很有趣,各種在windows編程里看不到的技巧在這里盡顯無余。在一個(gè)進(jìn)程里有許多的線程,這些線程共享進(jìn)程里的所有資源。包括數(shù)據(jù)空間,所以全局變量是為所有的線程所共享的。但如果線程里的全局變量為所有的線程所共享會出現(xiàn)一些問題。比如如果代碼量很大的話那么名字的命名都是一個(gè)問題。如果兩個(gè)線程有相同的全局
erron變量那么線程
2可以會用到線程
1的出錯提示。
這個(gè)問題可以通過創(chuàng)建線程的私有數(shù)據(jù)來解決(thread-specific Data,TSD)。一個(gè)線程里的TSD只有這個(gè)線程可以訪問。
TSD采用了一種稱之為私有數(shù)據(jù)的技術(shù),即一個(gè)鍵對應(yīng)多個(gè)數(shù)據(jù)值。意思就好比用一個(gè)數(shù)據(jù)結(jié)構(gòu),這個(gè)結(jié)構(gòu)的結(jié)構(gòu)名就是鍵值,在這個(gè)結(jié)構(gòu)里有許多的數(shù)據(jù),這些數(shù)據(jù)封閉在這個(gè)結(jié)構(gòu)里。線程可以通過這個(gè)結(jié)構(gòu)名即鍵值來訪問其所屬的數(shù)據(jù)結(jié)構(gòu)。
創(chuàng)建TSD有三個(gè)步驟:創(chuàng)建一個(gè)鍵(即創(chuàng)建一個(gè)數(shù)據(jù)結(jié)構(gòu)),為這個(gè)鍵設(shè)置線程的私有數(shù)據(jù)(即為這個(gè)結(jié)構(gòu)體里的數(shù)據(jù)賦值)。刪除鍵值。
三個(gè)步驟分別對應(yīng)的系統(tǒng)函數(shù)了:
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
int pthread_setspecific(pthread_key_t key, const void *value);
int pthread_key_delete(pthread_key_t key);
創(chuàng)建了TSD后線程可以用下面的函數(shù)來讀取數(shù)據(jù)。
void *pthread_getspecific(pthread_key_t key);
下面代碼演示創(chuàng)建TSD:
1 #include<stdio.h>
2 #include<string.h>
3 #include<pthread.h>
4
5 pthread_key_t key;
6 void *thread2(void *arg)
7 {
8 int tsd=5;
9 printf("thread %u is running\n",pthread_self());
10 pthread_setspecific(key,(void*)tsd);
11 printf("thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
12 }
13 void *thread1(void *arg)
14 {
15 int tsd=0;
16 pthread_t thid2;
17 printf("thread %u is running \n",pthread_self());
18 pthread_setspecific(key,(void*)tsd);
19 pthread_create(&thid2,NULL,thread2,NULL);
20 sleep(5);
21 printf("thread %u returns %\n",pthread_self(),pthread_getspecific(key));
22 }
23 int main()
24 {
25 pthread_t thid1;
26 printf("main thread begins running \n");
27 pthread_key_create(&key,NULL);
28 pthread_create(&thid1,NULL,thread1,NULL);
29 sleep(3);
30 pthread_key_delete(key);
31 printf("main thread exit\n");
32 return 0;
33 }
程序首先包涵所須的頭文件。程序分三個(gè)函數(shù),thread2(),thread1(),main()。線程2通過線程一的函數(shù)來創(chuàng)建。在main()函數(shù)里通過調(diào)用pthread_key_create()創(chuàng)建了一個(gè)TSD鍵值key。然后調(diào)用pthread_create()函數(shù)創(chuàng)建線程1。線程1開始運(yùn)行。在線程函數(shù)里有要保護(hù)的私有數(shù)據(jù)tsd=0;
通過調(diào)用pthread_key_setspecific()函數(shù)把tsd設(shè)置到鍵值key當(dāng)中。接著調(diào)用pthread_create()創(chuàng)建線程2。然后沉睡5秒,最后通過調(diào)用pthread_key_getspecific(),打印出鍵值。在線程2函數(shù)里先定義要保護(hù)的私有數(shù)據(jù)tsd=5;然后調(diào)用pthread_key_specific()函數(shù)設(shè)置tsd=5到key里。
在編譯的時(shí)候要用到pthread.a庫,形式為:
ong@ubuntu:~/myjc/myc$ gcc -o tsd tsd.c -lpthread