1. 程式人生 > >Linux多執行緒Pthread學習小結

Linux多執行緒Pthread學習小結

               

簡介

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(): 查詢執行緒自身執行緒標識號

詳細請參見:

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

多執行緒建立

參考程式碼:

[cpp] view plain copy print?
  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. }  
#include<stdio.h>#include<pthread.h>#include<string.h>#include<sys/types.h>#include<unistd.h>pthread_t main_tid;void print_ids(const char *str){    pid_t pid;      //程序id    pthread_t tid;  //執行緒id    pid = getpid();       //獲取當前程序id    tid = pthread_self(); //獲取當前執行緒id    printf("%s pid: %u tid: %u (0x%x)/n",                str,                (unsigned int)pid,                (unsigned int)tid,                (unsigned int)tid);}void *func(void *arg){    print_ids("new  thread:");    return ((void *)0);}int main(){    int err;    err = pthread_create(&main_tid, NULL, func, NULL); //建立執行緒    if(err != 0){        printf("create thread error: %s/n",strerror(err));        return 1;    }    printf("main thread: pid: %u tid: %u (0x%x)/n",                 (unsigned int)getpid(),                (unsigned int)pthread_self(),                (unsigned int)pthread_self());    print_ids("main thread:");    sleep(1);    return 0;} 

執行結果:

[[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)

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

多執行緒條件變數

參考程式碼:

[cpp] view plain copy print?
  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. }  
#include <stdio.h>#include <pthread.h>#include <unistd.h>pthread_mutex_t counter_lock;   //互斥鎖pthread_cond_t counter_nonzero; //條件變數int counter = 0;int estatus = -1;void *decrement_counter(void *argv);void *increment_counter(void *argv);//******* 主函式 *******//int main(int argc, char **argv){    printf("counter: %d/n", counter);    pthread_t thd1, thd2;    int ret;    //初始化    pthread_mutex_init(&counter_lock, NULL);    pthread_cond_init(&counter_nonzero, NULL);        ret = pthread_create(&thd1, NULL, decrement_counter, NULL); //建立執行緒1    if(ret){        perror("del:/n");        return 1;    }    ret = pthread_create(&thd2, NULL, increment_counter, NULL); //建立執行緒2    if(ret){        perror("inc: /n");        return 1;    }    int counter = 0;    while(counter != 10){        printf("counter(main): %d/n", counter); //主執行緒        sleep(1);        counter++;    }    pthread_exit(0);        return 0;}void *decrement_counter(void *argv){    printf("counter(decrement): %d/n", counter);    pthread_mutex_lock(&counter_lock);    while(counter == 0)        pthread_cond_wait(&counter_nonzero, &counter_lock); //進入阻塞(wait),等待啟用(signal)        printf("counter--(before): %d/n", counter);        counter--; //等待signal啟用後再執行    printf("counter--(after): %d/n", counter);        pthread_mutex_unlock(&counter_lock);     return &estatus;}void *increment_counter(void *argv){    printf("counter(increment): %d/n", counter);    pthread_mutex_lock(&counter_lock);    if(counter == 0)        pthread_cond_signal(&counter_nonzero); //啟用(signal)阻塞(wait)的執行緒(先執行完signal執行緒,然後再執行wait執行緒)    printf("counter++(before): %d/n", counter);        counter++;     printf("counter++(after): %d/n", counter);        pthread_mutex_unlock(&counter_lock);    return &estatus;}

執行結果:

[[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

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

多執行緒的建立特殊資料鍵

參考程式碼:

[cpp] view plain copy print?
  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. }  
#include <stdio.h>#include <pthread.h>#include <unistd.h>pthread_key_t key; //宣告引數keyvoid echomsg(void *arg) //析構處理函式{    printf("destruct executed in thread = %u, arg = %p/n",                 (unsigned int)pthread_self(),                arg);   }void *child_1(void *arg){    pthread_t tid;       tid = pthread_self();    printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);        pthread_setspecific(key, (void *)tid);  // 與key值繫結的value(tid)    printf("%s: thread %u returns %p/n",    // %p 表示輸出指標格式                 (char *)arg,                (unsigned int)tid,                 pthread_getspecific(key));  // 獲取key值的value    sleep(1);    return NULL;}void *child_2(void *arg){    pthread_t tid;       tid = pthread_self();    printf("%s: thread %u enter/n", (char *)arg, (unsigned int)tid);        pthread_setspecific(key, (void *)tid);    printf("%s: thread %u returns %p/n",                 (char *)arg,                (unsigned int)tid,                 pthread_getspecific(key));    sleep(1);    return NULL;}//******* 主函式 *******//int main(void){    pthread_t tid1, tid2;        printf("hello main/n");        pthread_key_create(&key, echomsg); //建立key        pthread_create(&tid1, NULL, child_1, (void *)"child_1"); //建立帶引數的執行緒,需要強制轉換    pthread_create(&tid2, NULL, child_2, (void *)"child_2");    sleep(3);    pthread_key_delete(key); //清除key    printf("bye main/n");        pthread_exit(0);    return 0;}

執行結果:

[[email protected] pthread]$ gcc -Wall -o pthread_setspecific pthread_setspecific.c -lpthread[[email protected] pthread]$ ./pthread_setspecific                                           hello mainchild_1: thread 1084229984 enterchild_1: thread 1084229984 returns 0x40a00960child_2: thread 1094719840 enterchild_2: thread 1094719840 returns 0x41401960destruct executed in thread = 1084229984, arg = 0x40a00960destruct executed in thread = 1094719840, arg = 0x41401960bye 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)參考網址:

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

多執行緒的建立特殊資料鍵

參考程式碼:

[cpp] view plain copy print?
  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. }  
#include <stdio.h>#include <pthread.h>#include <unistd.h>pthread_once_t once = PTHREAD_ONCE_INIT; //宣告變數//once_run()函式僅執行一次,且究竟在哪個執行緒中執行是不定的//儘管pthread_once(&once,once_run)出現在兩個執行緒中//函式原型:int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))void once_run(void){    printf("Func: %s in thread: %u/n",                 __func__,                 (unsigned int)pthread_self());}void *child_1(void *arg){    pthread_t tid;    tid = pthread_self();    pthread_once(&once, once_run); //呼叫once_run    printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);    return NULL;}void *child_2(void *arg){    pthread_t tid;    tid = pthread_self();    pthread_once(&once, once_run); //呼叫once_run    printf("%s: thread %d returns/n", (char *)arg, (unsigned int)tid);    return NULL;}//******* main *******//int main(void){    pthread_t tid1, tid2;    printf("hello main/n");    pthread_create(&tid1, NULL, child_1, (void *)"child_1");    pthread_create(&tid2, NULL, child_2, (void *)"child_2");    pthread_join(tid1, NULL);  //main主執行緒等待執行緒tid1返回    pthread_join(tid2, NULL);  //main主執行緒等待執行緒tid2返回    printf("bye main/n");    return 0;}

執行結果:

[email protected] pthread]$ gcc -Wall -o pthread_once pthread_once.c -lpthread[[email protected] pthread]$ ./pthread_once                                    hello mainFunc: once_run in thread: 1084229984child_1: thread 1084229984 returnschild_2: thread 1094719840 returnsbye main