c/c++: 多線程編程基礎講解(四)

來源:互聯網
上載者:User

http://blog.csdn.net/lzx_bupt/article/details/6913039

經過前面的幾個例子,是不是還少個線程建立時屬性參數沒有提到,見下文樣本:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4.   
  5. #include <iostream>  
  6. #include <pthread.h>  
  7.   
  8. using namespace std;  
  9.   
  10. #define NUM_THREADS 5  
  11.   
  12. void* say_hello(void* args)  
  13. {  
  14.     cout << "hello in thread " << *((int *)args) << endl;  
  15.     int status = 10 + *((int *)args);//將參數加10  
  16.     pthread_exit((void*)status);//由於線程建立時候提供了joinable參數,這裡可以在退出時添加退出的資訊:status供主程式提取該線程的結束資訊;  
  17. }  
  18.   
  19. int main()  
  20. {  
  21.     pthread_t tids[NUM_THREADS];  
  22.     int indexes[NUM_THREADS];  
  23.   
  24.     pthread_attr_t attr;//要想建立時加入參數,先聲明  
  25.     pthread_attr_init(&attr);//再初始化  
  26.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//聲明、初始化後第三步就是設定你想要指定線程屬性參數,這個參數表明這個線程是可以join串連的,join功能表示主程式可以等線程結束後再去做某事,實現了主程式和線程同步功能,這個深層理解必須通過圖示才能解釋;參閱其他資料吧  
  27.   
  28.     for(int i = 0; i < NUM_THREADS; ++i)  
  29.     {  
  30.         indexes[i] = i;  
  31.         int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//這裡四個參數都齊全了,更多的配置仍需查閱資料;  
  32.         if (ret != 0)  
  33.         {  
  34.            cout << "pthread_create error: error_code=" << ret << endl;  
  35.         }  
  36.     }  
  37.   
  38.     pthread_attr_destroy(&attr);//參數使用完了就可以銷毀了,必須銷毀哦,防止記憶體泄露;  
  39.   
  40.     void *status;  
  41.     for (int i = 0; i < NUM_THREADS; ++i)  
  42.     {  
  43.         int ret = pthread_join(tids[i], &status);//前面建立了線程,這裡主程式想要join每個線程後取得每個線程的退出資訊status;  
  44.         if (ret != 0)  
  45.         {  
  46.             cout << "pthread_join error: error_code=" << ret << endl;  
  47.         }  
  48.         else  
  49.         {  
  50.             cout << "pthread_join get status: " << (long)status << endl;  
  51.         }  
  52.     }  
  53. }  

編譯運行 g++ -lpthread -o ex_join ex_join.cpp

結果:

[plain] view plaincopy
  1. hello in thread 4  
  2. hello in thread 3  
  3. hello in thread 2  
  4. hello in thread 1  
  5. hello in thread 0  
  6. pthread_join get status: 10  
  7. pthread_join get status: 11  
  8. pthread_join get status: 12  
  9. pthread_join get status: 13  
  10. pthread_join get status: 14  

體會一下join的功能吧

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.