linux下的線程真是很有趣,各種在windows編程里看不到的技巧在這里盡顯無余。在一個進程里有許多的線程,這些線程共享進程里的所有資源。包括數(shù)據(jù)空間,所以全局變量是為所有的線程所共享的。但如果線程里的全局變量為所有的線程所共享會出現(xiàn)一些問題。比如如果代碼量很大的話那么名字的命名都是一個問題。如果兩個線程有相同的全局
erron變量那么線程
2可以會用到線程
1的出錯提示。
這個問題可以通過創(chuàng)建線程的私有數(shù)據(jù)來解決(thread-specific Data,TSD)。一個線程里的TSD只有這個線程可以訪問。
TSD采用了一種稱之為私有數(shù)據(jù)的技術,即一個鍵對應多個數(shù)據(jù)值。意思就好比用一個數(shù)據(jù)結構,這個結構的結構名就是鍵值,在這個結構里有許多的數(shù)據(jù),這些數(shù)據(jù)封閉在這個結構里。線程可以通過這個結構名即鍵值來訪問其所屬的數(shù)據(jù)結構。
創(chuàng)建TSD有三個步驟:創(chuàng)建一個鍵(即創(chuàng)建一個數(shù)據(jù)結構),為這個鍵設置線程的私有數(shù)據(jù)(即為這個結構體里的數(shù)據(jù)賦值)。刪除鍵值。
三個步驟分別對應的系統(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 }
程序首先包涵所須的頭文件。程序分三個函數(shù),thread2(),thread1(),main()。線程2通過線程一的函數(shù)來創(chuàng)建。在main()函數(shù)里通過調用pthread_key_create()創(chuàng)建了一個TSD鍵值key。然后調用pthread_create()函數(shù)創(chuàng)建線程1。線程1開始運行。在線程函數(shù)里有要保護的私有數(shù)據(jù)tsd=0;
通過調用pthread_key_setspecific()函數(shù)把tsd設置到鍵值key當中。接著調用pthread_create()創(chuàng)建線程2。然后沉睡5秒,最后通過調用pthread_key_getspecific(),打印出鍵值。在線程2函數(shù)里先定義要保護的私有數(shù)據(jù)tsd=5;然后調用pthread_key_specific()函數(shù)設置tsd=5到key里。
在編譯的時候要用到pthread.a庫,形式為:
ong@ubuntu:~/myjc/myc$ gcc -o tsd tsd.c -lpthread