C/C++ Linux下多線程編程 #include

轉自:點擊打開鏈接

1.最基礎,進程同時創建5個線程,各自調用同一個函數

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h> //多線程相關操作頭文件,可移植衆多平臺  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5 //線程數  
  7.   
  8. void* say_hello( void* args )  
  9. {  
  10.     cout << "hello..." << endl;  
  11. } //函數返回的是函數指針,便於後面作爲參數  
  12.   
  13. int main()  
  14. {  
  15.     pthread_t tids[NUM_THREADS]; //線程id  
  16.     for( int i = 0; i < NUM_THREADS; ++i )  
  17.     {  
  18.         int ret = pthread_create( &tids[i], NULL, say_hello, NULL ); //參數:創建的線程id,線程參數,線程運行函數的起始地址,運行函數的參數  
  19.         if( ret != 0 ) //創建線程成功返回0  
  20.         {  
  21.             cout << "pthread_create error:error_code=" << ret << endl;  
  22.         }  
  23.     }  
  24.     pthread_exit( NULL ); //等待各個線程退出後,進程才結束,否則進程強制結束,線程處於未終止的狀態  
  25. }  
輸入命令:g++ -o muti_thread_test_1 muti_thread_test_1.cpp -lpthread

注意:

1)此爲c++程序,故用g++來編譯生成可執行文件,並且要調用處理多線程操作相關的靜態鏈接庫文件pthread。

2)-lpthread 編譯選項到位置可任意,如g++ -lpthread -o muti_thread_test_1 muti_thread_test_1.cpp

3)注意gcc和g++的區別,轉到此文:點擊打開鏈接

測試結果:

[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_1  
  2. hello...hello...  
  3. hello...  
  4. hello...  
  5.   
  6. hello...  
[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_1  
  2. hello...hello...hello...  
  3.   
  4. hello...  
  5. hello...  

可知,兩次運行的結果會有差別,這不是多線程的特點吧?這顯然沒有同步?還有待進一步探索...


2.線程調用到函數在一個類中,那必須將該函數聲明爲靜態函數函數

因爲靜態成員函數屬於靜態全局區,線程可以共享這個區域,故可以各自調用。

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. class Hello  
  9. {  
  10. public:  
  11.     static void* say_hello( void* args )  
  12.     {  
  13.         cout << "hello..." << endl;  
  14.     }  
  15. };  
  16.   
  17. int main()  
  18. {  
  19.     pthread_t tids[NUM_THREADS];  
  20.     for( int i = 0; i < NUM_THREADS; ++i )  
  21.     {  
  22.         int ret = pthread_create( &tids[i], NULL, Hello::say_hello, NULL );  
  23.         if( ret != 0 )  
  24.         {  
  25.             cout << "pthread_create error:error_code" << ret << endl;  
  26.         }  
  27.     }  
  28.     pthread_exit( NULL );  
  29. }  

測試結果:

[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_2  
  2. hello...  
  3. hello...  
  4. hello...  
  5. hello...  
  6. hello...  
[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_2  
  2. hello...hello...hello...  
  3.   
  4.   
  5. hello...  
  6. hello...  

兩次運行的結果會有差別,這顯然沒有同步!


3.如何在線程調用函數時傳入參數呢?

先看下面修改的代碼,傳入線程編號作爲參數:

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h> //多線程相關操作頭文件,可移植衆多平臺  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5 //線程數  
  7.   
  8. void* say_hello( void* args )  
  9. {  
  10.     int i = *( (int*)args ); //對傳入的參數進行強制類型轉換,由無類型指針轉變爲整形指針,再用*讀取其指向到內容  
  11.     cout << "hello in " << i <<  endl;  
  12. } //函數返回的是函數指針,便於後面作爲參數  
  13.   
  14. int main()  
  15. {  
  16.     pthread_t tids[NUM_THREADS]; //線程id  
  17.     cout << "hello in main.." << endl;  
  18.     for( int i = 0; i < NUM_THREADS; ++i )  
  19.     {  
  20.         int ret = pthread_create( &tids[i], NULL, say_hello, (void*)&i ); //傳入到參數必須強轉爲void*類型,即無類型指針,&i表示取i的地址,即指向i的指針  
  21.         cout << "Current pthread id = " << tids[i] << endl; //用tids數組打印創建的進程id信息  
  22.         if( ret != 0 ) //創建線程成功返回0  
  23.         {  
  24.             cout << "pthread_create error:error_code=" << ret << endl;  
  25.         }  
  26.     }  
  27.     pthread_exit( NULL ); //等待各個線程退出後,進程才結束,否則進程強制結束,線程處於未終止的狀態  
  28. }  
測試結果:
[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_3  
  2. hello in main..  
  3. Current pthread id = 3078458224  
  4. Current pthread id = 3070065520  
  5. hello in hello in 2  
  6. 1  
  7. Current pthread id = hello in 2  
  8. 3061672816  
  9. Current pthread id = 3053280112  
  10. hello in 4  
  11. Current pthread id = hello in 4  
  12. 3044887408  
顯然不是想要的結果,調用順序很亂,這是爲什麼呢?

這是因爲多線程到緣故,主進程還沒開始對i賦值,線程已經開始跑了...?

修改代碼如下:

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h> //多線程相關操作頭文件,可移植衆多平臺  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5 //線程數  
  7.   
  8. void* say_hello( void* args )  
  9. {  
  10.     cout << "hello in thread " << *( (int *)args ) <<  endl;  
  11. } //函數返回的是函數指針,便於後面作爲參數  
  12.   
  13. int main()  
  14. {  
  15.     pthread_t tids[NUM_THREADS]; //線程id  
  16.     int indexes[NUM_THREADS]; //用來保存i的值避免被修改  
  17.   
  18.     for( int i = 0; i < NUM_THREADS; ++i )  
  19.     {  
  20.         indexes[i] = i;  
  21.         int ret = pthread_create( &tids[i], NULL, say_hello, (void*)&(indexes[i]) );  
  22.         if( ret != 0 ) //創建線程成功返回0  
  23.         {  
  24.             cout << "pthread_create error:error_code=" << ret << endl;  
  25.         }  
  26.     }  
  27.     for( int i = 0; i < NUM_THREADS; ++i )  
  28.         pthread_join( tids[i], NULL ); //pthread_join用來等待一個線程的結束,是一個線程阻塞的函數  
  29. }  
測試結果:

[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_3  
  2. hello in thread hello in thread hello in thread hello in thread hello in thread 30124  

這是正常的嗎?感覺還是有問題...待續

代碼中如果沒有pthread_join主線程會很快結束從而使整個進程結束,從而使創建的線程沒有機會開始執行就結束了。加入pthread_join後,主線程會一直等待直到等待的線程結束自己才結束,使創建的線程有機會執行


4.線程創建時屬性參數的設置pthread_attr_t及join功能的使用

線程的屬性由結構體pthread_attr_t進行管理。

typedef struct
{
    int                           detachstate;     線程的分離狀態
    int                          schedpolicy;   線程調度策略
    struct sched_param      schedparam;   線程的調度參數
    int inheritsched; 線程的繼承性 
    int scope; 線程的作用域 
    size_t guardsize; 線程棧末尾的警戒緩衝區大小 
    int stackaddr_set; void * stackaddr; 線程棧的位置 
    size_t stacksize; 線程棧的大小
}pthread_attr_t;

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. void* say_hello( void* args )  
  9. {  
  10.     cout << "hello in thread " << *(( int * )args) << endl;  
  11.     int status = 10 + *(( int * )args); //線程退出時添加退出的信息,status供主程序提取該線程的結束信息  
  12.     pthread_exit( ( void* )status );   
  13. }  
  14.   
  15. int main()  
  16. {  
  17.     pthread_t tids[NUM_THREADS];  
  18.     int indexes[NUM_THREADS];  
  19.       
  20.     pthread_attr_t attr; //線程屬性結構體,創建線程時加入的參數  
  21.     pthread_attr_init( &attr ); //初始化  
  22.     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是設置你想要指定線程屬性參數,這個參數表明這個線程是可以join連接的,join功能表示主程序可以等線程結束後再去做某事,實現了主程序和線程同步功能  
  23.     for( int i = 0; i < NUM_THREADS; ++i )  
  24.     {  
  25.         indexes[i] = i;  
  26.         int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) );  
  27.         if( ret != 0 )  
  28.         {  
  29.         cout << "pthread_create error:error_code=" << ret << endl;  
  30.     }  
  31.     }   
  32.     pthread_attr_destroy( &attr ); //釋放內存   
  33.     void *status;  
  34.     for( int i = 0; i < NUM_THREADS; ++i )  
  35.     {  
  36.     int ret = pthread_join( tids[i], &status ); //主程序join每個線程後取得每個線程的退出信息status  
  37.     if( ret != 0 )  
  38.     {  
  39.         cout << "pthread_join error:error_code=" << ret << endl;  
  40.     }  
  41.     else  
  42.     {  
  43.         cout << "pthread_join get status:" << (long)status << endl;  
  44.     }  
  45.     }  
  46. }  
測試結果:

[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_4  
  2. hello in thread hello in thread hello in thread hello in thread 0hello in thread 321  
  3.   
  4.   
  5.   
  6. 4  
  7. pthread_join get status:10  
  8. pthread_join get status:11  
  9. pthread_join get status:12  
  10. pthread_join get status:13  
  11. pthread_join get status:14  

5.互斥鎖的實現
互斥鎖是實現線程同步的一種機制,只要在臨界區前後對資源加鎖就能阻塞其他進程的訪問。

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. int sum = 0; //定義全局變量,讓所有線程同時寫,這樣就需要鎖機制  
  9. pthread_mutex_t sum_mutex; //互斥鎖  
  10.   
  11. void* say_hello( void* args )  
  12. {  
  13.     cout << "hello in thread " << *(( int * )args) << endl;  
  14.     pthread_mutex_lock( &sum_mutex ); //先加鎖,再修改sum的值,鎖被佔用就阻塞,直到拿到鎖再修改sum;  
  15.     cout << "before sum is " << sum << " in thread " << *( ( int* )args ) << endl;  
  16.     sum += *( ( int* )args );  
  17.     cout << "after sum is " << sum << " in thread " << *( ( int* )args ) << endl;  
  18.     pthread_mutex_unlock( &sum_mutex ); //釋放鎖,供其他線程使用  
  19.     pthread_exit( 0 );   
  20. }  
  21.   
  22. int main()  
  23. {  
  24.     pthread_t tids[NUM_THREADS];  
  25.     int indexes[NUM_THREADS];  
  26.       
  27.     pthread_attr_t attr; //線程屬性結構體,創建線程時加入的參數  
  28.     pthread_attr_init( &attr ); //初始化  
  29.     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是設置你想要指定線程屬性參數,這個參數表明這個線程是可以join連接的,join功能表示主程序可以等線程結束後再去做某事,實現了主程序和線程同步功能  
  30.     pthread_mutex_init( &sum_mutex, NULL ); //對鎖進行初始化      
  31.   
  32.     for( int i = 0; i < NUM_THREADS; ++i )  
  33.     {  
  34.         indexes[i] = i;  
  35.         int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) ); //5個進程同時去修改sum  
  36.         if( ret != 0 )  
  37.         {  
  38.         cout << "pthread_create error:error_code=" << ret << endl;  
  39.     }  
  40.     }   
  41.     pthread_attr_destroy( &attr ); //釋放內存   
  42.     void *status;  
  43.     for( int i = 0; i < NUM_THREADS; ++i )  
  44.     {  
  45.     int ret = pthread_join( tids[i], &status ); //主程序join每個線程後取得每個線程的退出信息status  
  46.     if( ret != 0 )  
  47.     {  
  48.         cout << "pthread_join error:error_code=" << ret << endl;  
  49.     }  
  50.     }  
  51.     cout << "finally sum is " << sum << endl;  
  52.     pthread_mutex_destroy( &sum_mutex ); //註銷鎖  
  53. }  
測試結果:
[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_5  
  2. hello in thread hello in thread hello in thread 410  
  3. before sum is hello in thread 0 in thread 4  
  4. after sum is 4 in thread 4hello in thread   
  5.   
  6.   
  7. 2  
  8. 3  
  9. before sum is 4 in thread 1  
  10. after sum is 5 in thread 1  
  11. before sum is 5 in thread 0  
  12. after sum is 5 in thread 0  
  13. before sum is 5 in thread 2  
  14. after sum is 7 in thread 2  
  15. before sum is 7 in thread 3  
  16. after sum is 10 in thread 3  
  17. finally sum is 10  
可知,sum的訪問和修改順序是正常的,這就達到了多線程的目的了,但是線程的運行順序是混亂的,混亂就是正常?

6.信號量的實現
信號量是線程同步的另一種實現機制,信號量的操作有signal和wait,本例子採用條件信號變量pthread_cond_t tasks_cond;
信號量的實現也要給予鎖機制。

[html] view plain copy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3. #include <stdio.h>  
  4.   
  5. using namespace std;  
  6.   
  7. #define BOUNDARY 5  
  8.   
  9. int tasks = 10;  
  10. pthread_mutex_t tasks_mutex; //互斥鎖  
  11. pthread_cond_t tasks_cond; //條件信號變量,處理兩個線程間的條件關係,當task>5,hello2處理,反之hello1處理,直到task減爲0  
  12.   
  13. void* say_hello2( void* args )  
  14. {  
  15.     pthread_t pid = pthread_self(); //獲取當前線程id  
  16.     cout << "[" << pid << "] hello in thread " <<  *( ( int* )args ) << endl;  
  17.       
  18.     bool is_signaled = false; //sign  
  19.     while(1)  
  20.     {  
  21.     pthread_mutex_lock( &tasks_mutex ); //加鎖  
  22.     if( tasks > BOUNDARY )  
  23.     {  
  24.         cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl;  
  25.         --tasks; //modify  
  26.     }  
  27.     else if( !is_signaled )  
  28.     {  
  29.         cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;  
  30.         pthread_cond_signal( &tasks_cond ); //signal:向hello1發送信號,表明已經>5  
  31.         is_signaled = true; //表明信號已發送,退出此線程  
  32.     }  
  33.     pthread_mutex_unlock( &tasks_mutex ); //解鎖  
  34.     if( tasks == 0 )  
  35.         break;  
  36.     }      
  37. }  
  38.   
  39. void* say_hello1( void* args )  
  40. {  
  41.     pthread_t pid = pthread_self(); //獲取當前線程id  
  42.     cout << "[" << pid << "] hello in thread " <<  *( ( int* )args ) << endl;  
  43.   
  44.     while(1)  
  45.     {  
  46.         pthread_mutex_lock( &tasks_mutex ); //加鎖  
  47.         if( tasks > BOUNDARY )  
  48.         {  
  49.         cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;  
  50.         pthread_cond_wait( &tasks_cond, &tasks_mutex ); //wait:等待信號量生效,接收到信號,向hello2發出信號,跳出wait,執行後續   
  51.         }  
  52.         else  
  53.         {  
  54.         cout << "[" << pid << "] take task: " << tasks << " in thread " << *( (int*)args ) << endl;  
  55.             --tasks;  
  56.     }  
  57.         pthread_mutex_unlock( &tasks_mutex ); //解鎖  
  58.         if( tasks == 0 )  
  59.             break;  
  60.     }   
  61. }  
  62.   
  63.   
  64. int main()  
  65. {  
  66.     pthread_attr_t attr; //線程屬性結構體,創建線程時加入的參數  
  67.     pthread_attr_init( &attr ); //初始化  
  68.     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是設置你想要指定線程屬性參數,這個參數表明這個線程是可以join連接的,join功能表示主程序可以等線程結束後再去做某事,實現了主程序和線程同步功能  
  69.     pthread_cond_init( &tasks_cond, NULL ); //初始化條件信號量  
  70.     pthread_mutex_init( &tasks_mutex, NULL ); //初始化互斥量  
  71.     pthread_t tid1, tid2; //保存兩個線程id  
  72.     int index1 = 1;  
  73.     int ret = pthread_create( &tid1, &attr, say_hello1, ( void* )&index1 );  
  74.     if( ret != 0 )  
  75.     {  
  76.         cout << "pthread_create error:error_code=" << ret << endl;  
  77.     }  
  78.     int index2 = 2;  
  79.     ret = pthread_create( &tid2, &attr, say_hello2, ( void* )&index2 );  
  80.     if( ret != 0 )  
  81.     {  
  82.         cout << "pthread_create error:error_code=" << ret << endl;  
  83.     }  
  84.     pthread_join( tid1, NULL ); //連接兩個線程  
  85.     pthread_join( tid2, NULL );   
  86.   
  87.     pthread_attr_destroy( &attr ); //釋放內存   
  88.     pthread_mutex_destroy( &tasks_mutex ); //註銷鎖  
  89.     pthread_cond_destroy( &tasks_cond ); //正常退出  
  90. }  
測試結果:
先在線程2中執行say_hello2,再跳轉到線程1中執行say_hello1,直到tasks減到0爲止。

[html] view plain copy
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_6  
  2. [3069823856] hello in thread 2  
  3. [3078216560] hello in thread 1[3069823856] take task: 10 in thread 2  
  4.   
  5. [3069823856] take task: 9 in thread 2  
  6. [3069823856] take task: 8 in thread 2  
  7. [3069823856] take task: 7 in thread 2  
  8. [3069823856] take task: 6 in thread 2  
  9. [3069823856] pthread_cond_signal in thread 2  
  10. [3078216560] take task: 5 in thread 1  
  11. [3078216560] take task: 4 in thread 1  
  12. [3078216560] take task: 3 in thread 1  
  13. [3078216560] take task: 2 in thread 1  
  14. [3078216560] take task: 1 in thread 1  
到此,對多線程編程有了一個初步的瞭解,當然還有其他實現線程同步的機制,有待進一步探索。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章