http://blog.csdn.net/lzx_bupt/article/details/6913039
經過前面的幾個例子,是不是還少個線程建立時屬性參數沒有提到,見下文樣本:
[cpp] view plaincopy
- #include <iostream>
- #include <pthread.h>
-
-
- #include <iostream>
- #include <pthread.h>
-
- using namespace std;
-
- #define NUM_THREADS 5
-
- void* say_hello(void* args)
- {
- cout << "hello in thread " << *((int *)args) << endl;
- int status = 10 + *((int *)args);//將參數加10
- pthread_exit((void*)status);//由於線程建立時候提供了joinable參數,這裡可以在退出時添加退出的資訊:status供主程式提取該線程的結束資訊;
- }
-
- int main()
- {
- pthread_t tids[NUM_THREADS];
- int indexes[NUM_THREADS];
-
- pthread_attr_t attr;//要想建立時加入參數,先聲明
- pthread_attr_init(&attr);//再初始化
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//聲明、初始化後第三步就是設定你想要指定線程屬性參數,這個參數表明這個線程是可以join串連的,join功能表示主程式可以等線程結束後再去做某事,實現了主程式和線程同步功能,這個深層理解必須通過圖示才能解釋;參閱其他資料吧
-
- for(int i = 0; i < NUM_THREADS; ++i)
- {
- indexes[i] = i;
- int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//這裡四個參數都齊全了,更多的配置仍需查閱資料;
- if (ret != 0)
- {
- cout << "pthread_create error: error_code=" << ret << endl;
- }
- }
-
- pthread_attr_destroy(&attr);//參數使用完了就可以銷毀了,必須銷毀哦,防止記憶體泄露;
-
- void *status;
- for (int i = 0; i < NUM_THREADS; ++i)
- {
- int ret = pthread_join(tids[i], &status);//前面建立了線程,這裡主程式想要join每個線程後取得每個線程的退出資訊status;
- if (ret != 0)
- {
- cout << "pthread_join error: error_code=" << ret << endl;
- }
- else
- {
- cout << "pthread_join get status: " << (long)status << endl;
- }
- }
- }
編譯運行 g++ -lpthread -o ex_join ex_join.cpp
結果:
[plain] view plaincopy
- hello in thread 4
- hello in thread 3
- hello in thread 2
- hello in thread 1
- hello in thread 0
- pthread_join get status: 10
- pthread_join get status: 11
- pthread_join get status: 12
- pthread_join get status: 13
- pthread_join get status: 14
體會一下join的功能吧