Linux下線程總結

簡介

POSIX thread 簡稱爲pthread,Posix線程是一個POSIX標準線程.該標準定義內部API創建和操縱線程.

 

作用 

線程庫實行了POSIX線程標準通常稱爲pthreads.pthreads是最常用的POSIX系統如Linux和Unix,而微軟Windowsimplementations同時存在.舉例來說,pthreads-w32可支持MIDP的pthread   

Pthreads定義了一套 C程序語言類型、函數與常量,它以 pthread.h 頭文件和一個線程庫實現。

 

數據類型 

pthread_t:線程句柄   

pthread_attr_t:線程屬性 

線程操縱函數(簡介起見,省略參數)

pthread_create():創建一個線程   

pthread_exit():終止當前線程   

pthread_cancel():中斷另外一個線程的運行   

pthread_join():阻塞當前的線程,直到另外一個線程運行結束   

pthread_attr_init():初始化線程的屬性   

pthread_attr_setdetachstate():設置脫離狀態的屬性(決定這個線程在終止時是否可以被結合)

pthread_attr_getdetachstate():獲取脫離狀態的屬性   

pthread_attr_destroy():刪除線程的屬性   

pthread_kill():向線程發送一個信號

 

同步函數

用於 mutex 和條件變量   

pthread_mutex_init() 初始化互斥鎖   

pthread_mutex_destroy() 刪除互斥鎖   

pthread_mutex_lock():佔有互斥鎖(阻塞操作)   

pthread_mutex_trylock():試圖佔有互斥鎖(不阻塞操作)。當互斥鎖空閒時將佔有該鎖;否則立即返回  

pthread_mutex_unlock(): 釋放互斥鎖   

pthread_cond_init():初始化條件變量   

pthread_cond_destroy():銷燬條件變量   

pthread_cond_wait(): 等待條件變量的特殊條件發生

pthread_cond_signal(): 喚醒第一個調用pthread_cond_wait()而進入睡眠的線程      

Thread-local storage(或者以Pthreads術語,稱作 線程特有數據):   

pthread_key_create(): 分配用於標識進程中線程特定數據的鍵   

pthread_setspecific(): 爲指定線程特定數據鍵設置線程特定綁定   

pthread_getspecific(): 獲取調用線程的鍵綁定,並將該綁定存儲在 value 指向的位置中   

pthread_key_delete(): 銷燬現有線程特定數據鍵

 

與一起工作的工具函數

pthread_equal(): 對兩個線程的線程標識號進行比較   

pthread_detach(): 分離線程   

pthread_self(): 查詢線程自身線程標識號

 

詳細請參見:

Linux多線程pthread:     http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5920936.aspx

Pthread多線程學習小結: http://blog.csdn.net/Sunboy_2050/archive/2010/10/04/5921003.aspx

===================================================================

 

多線程創建

參考代碼:

  1. #include<stdio.h>

  2. #include<pthread.h>

  3. #include<string.h>

  4. #include<sys/types.h>

  5. #include<unistd.h>

  6. pthread_t main_tid;  

  7. void print_ids(constchar *str)  

  8. {  

  9.     pid_t pid;      //進程id

  10.     pthread_t tid;  //線程id

  11.     pid = getpid();       //獲取當前進程id

  12.     tid = pthread_self(); //獲取當前線程id

  13.     printf("%s pid: %u tid: %u (0x%x)/n",  

  14.                 str,  

  15.                 (unsigned int)pid,  

  16.                 (unsigned int)tid,  

  17.                 (unsigned int)tid);  

  18. }  

  19. void *func(void *arg)  

  20. {  

  21.     print_ids("new  thread:");  

  22. return ((void *)0);  

  23. }  

  24. int main()  

  25. {  

  26. int err;  

  27.     err = pthread_create(&main_tid, NULL, func, NULL); //創建線程

  28. if(err != 0){  

  29.         printf("create thread error: %s/n",strerror(err));  

  30. return 1;  

  31.     }  

  32.     printf("main thread: pid: %u tid: %u (0x%x)/n",   

  33.                 (unsigned int)getpid(),  

  34.                 (unsigned int)pthread_self(),  

  35.                 (unsigned int)pthread_self());  

  36.     print_ids("main thread:");  

  37.     sleep(1);  

  38. return 0;  

  39. }  

運行結果:

[[email protected] pthread]$ gcc -Wall -o pthread_create pthread_create.c -lpthread   

[[email protected] pthread]$ ./pthread_create 

main thread: pid: 12531 tid: 2505487232 (0x9556b380)

main thread: pid: 12531 tid: 2505487232 (0x9556b380)

new  thread: pid: 12531 tid: 1084229984 (0x40a00960)

 

===================================================================

 

多線程條件變量

參考代碼:

 

  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4. pthread_mutex_t counter_lock;   //互斥鎖

  5. pthread_cond_t counter_nonzero; //條件變量

  6. int counter = 0;  

  7. int estatus = -1;  

  8. void *decrement_counter(void *argv);  

  9. void *increment_counter(void *argv);  

  10. //******* 主函數 *******//

  11. int main(int argc, char **argv)  

  12. {  

  13.     printf("counter: %d/n", counter);  

  14.     pthread_t thd1, thd2;  

  15. int ret;  

  16. //初始化

  17.     pthread_mutex_init(&counter_lock, NULL);  

  18.     pthread_cond_init(&counter_nonzero, NULL);  

  19.     ret = pthread_create(&thd1, NULL, decrement_counter, NULL); //創建線程1

  20. if(ret){  

  21.         perror("del:/n");  

  22. return 1;  

  23.     }  

  24.     ret = pthread_create(&thd2, NULL, increment_counter, NULL); //創建線程2

  25. if(ret){  

  26.         perror("inc: /n");  

  27. return 1;  

  28.     }  

  29. int counter = 0;  

  30. while(counter != 10){  

  31.         printf("counter(main): %d/n", counter); //主線程

  32.         sleep(1);  

  33.         counter++;  

  34.     }  

  35.     pthread_exit(0);  

  36. return 0;  

  37. }  

  38. void *decrement_counter(void *argv)  

  39. {  

  40.     printf("counter(decrement): %d/n", counter);  

  41.     pthread_mutex_lock(&counter_lock);  

  42. while(counter == 0)  

  43.         pthread_cond_wait(&counter_nonzero, &counter_lock); //進入阻塞(wait),等待激活(signal)

  44.     printf("counter--(before): %d/n", counter);      

  45.     counter--; //等待signal激活後再執行

  46.     printf("counter--(after): %d/n", counter);      

  47.     pthread_mutex_unlock(&counter_lock);   

  48. return &estatus;  

  49. }  

  50. void *increment_counter(void *argv)  

  51. {  

  52.     printf("counter(increment): %d/n", counter);  

  53.     pthread_mutex_lock(&counter_lock);  

  54. if(counter == 0)  

  55.         pthread_cond_signal(&counter_nonzero); //激活(signal)阻塞(wait)的線程(先執行完signal線程,然後再執行wait線程)

  56.     printf("counter++(before): %d/n", counter);      

  57.     counter++;   

  58.     printf("counter++(after): %d/n", counter);      

  59.     pthread_mutex_unlock(&counter_lock);  

  60. return &estatus;  

  61. }  

 

運行結果:

[[email protected] pthread]$ gcc -Wall -o pthread_cond2 pthread_cond2.c -lpthread

[[email protected] pthread]$ ./pthread_cond2 

counter: 0

counter(main): 0

counter(decrement): 0

counter(increment): 0

counter++(before): 0

counter++(after): 1

counter--(before): 1

counter--(after): 0

counter(main): 1

counter(main): 2

counter(main): 3

counter(main): 4

counter(main): 5

counter(main): 6

counter(main): 7

counter(main): 8

counter(main): 9

 

詳細解釋,請見:http://blog.csdn.net/Sunboy_2050/archive/2010/11/24/6031723.aspx

===================================================================

 

多線程的創建特殊數據鍵

參考代碼:

  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4. pthread_key_t key; //聲明參數key

  5. void echomsg(void *arg) //析構處理函數

  6. {  

  7.     printf("destruct executed in thread = %u, arg = %p/n",   

  8.                 (unsigned int)pthread_self(),  

  9.                 arg);     

  10. }  

  11. void *child_1(void *arg)  

  12. {  

  13.     pthread_t tid;  

  14.     tid = pthread_self();  

  15.     printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);  

  16.     pthread_setspecific(key, (void *)tid);  // 與key值綁定的value(tid)

  17.     printf("%s: thread %u returns %p/n",    // %p 表示輸出指針格式 

  18.                 (char *)arg,  

  19.                 (unsigned int)tid,   

  20.                 pthread_getspecific(key));  // 獲取key值的value

  21.     sleep(1);  

  22. return NULL;  

  23. }  

  24. void *child_2(void *arg)  

  25. {  

  26.     pthread_t tid;  

  27.     tid = pthread_self();  

  28.     printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);  

  29.     pthread_setspecific(key, (void *)tid);  

  30.     printf("%s: thread %u returns %p/n",   

  31.                 (char *)arg,  

  32.                 (unsigned int)tid,   

  33.                 pthread_getspecific(key));  

  34.     sleep(1);  

  35. return NULL;  

  36. }  

  37. //******* 主函數 *******//

  38. int main(void)  

  39. {  

  40.     pthread_t tid1, tid2;  

  41.     printf("hello main/n");  

  42.     pthread_key_create(&key, echomsg); //創建key

  43.     pthread_create(&tid1, NULL, child_1, (void *)"child_1"); //創建帶參數的線程,需要強制轉換

  44.     pthread_create(&tid2, NULL, child_2, (void *)"child_2");  

  45.     sleep(3);  

  46.     pthread_key_delete(key); //清除key

  47.     printf("bye main/n");  

  48.     pthread_exit(0);  

  49. return 0;  

  50. }  

運行結果:

[[email protected] pthread]$ gcc -Wall -o pthread_setspecific pthread_setspecific.c -lpthread
[[email protected] pthread]$ ./pthread_setspecific                                           
hello main
child_1: thread 1084229984 enter
child_1: thread 1084229984 returns 0x40a00960
child_2: thread 1094719840 enter
child_2: thread 1094719840 returns 0x41401960
destruct executed in thread = 1084229984, arg = 0x40a00960
destruct executed in thread = 1094719840, arg = 0x41401960
bye main

 

附加參考——函數原型:

Posix定義了兩個API分別用來創建和註銷TSD:

int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *))
註銷一個TSD採用如下API:
int pthread_key_delete(pthread_key_t key)
int pthread_setspecific(pthread_key_t key, const void *pointer)
void * pthread_getspecific(pthread_key_t key)
參考網址:

 

===================================================================

多線程的創建特殊數據鍵

參考代碼:

 

  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4. pthread_once_t once = PTHREAD_ONCE_INIT; //聲明變量

  5. //once_run()函數僅執行一次,且究竟在哪個線程中執行是不定的

  6. //儘管pthread_once(&once,once_run)出現在兩個線程中

  7. //函數原型:int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))

  8. void once_run(void)  

  9. {  

  10.     printf("Func: %s in thread: %u/n",   

  11.                 __func__,   

  12.                 (unsigned int)pthread_self());  

  13. }  

  14. void *child_1(void *arg)  

  15. {  

  16.     pthread_t tid;  

  17.     tid = pthread_self();  

  18.     pthread_once(&once, once_run); //調用once_run

  19.     printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);  

  20. return NULL;  

  21. }  

  22. void *child_2(void *arg)  

  23. {  

  24.     pthread_t tid;  

  25.     tid = pthread_self();  

  26.     pthread_once(&once, once_run); //調用once_run

  27.     printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);  

  28. return NULL;  

  29. }  

  30. //******* main *******//

  31. int main(void)  

  32. {  

  33.     pthread_t tid1, tid2;  

  34.     printf("hello main/n");  

  35.     pthread_create(&tid1, NULL, child_1, (void *)"child_1");  

  36.     pthread_create(&tid2, NULL, child_2, (void *)"child_2");  

  37.     pthread_join(tid1, NULL);  //main主線程等待線程tid1返回

  38.     pthread_join(tid2, NULL);  //main主線程等待線程tid2返回

  39.     printf("bye main/n");  

  40. return 0;  

  41. }  

 

運行結果:

[email protected] pthread]$ gcc -Wall -o pthread_once pthread_once.c -lpthread
[[email protected] pthread]$ ./pthread_once                                    
hello main
Func: once_run in thread: 1084229984
child_1: thread 1084229984 returns
child_2: thread 1094719840 returns
bye main


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章