代碼如下:#include<pthread.h>#include<stdio.h>#define MAX_THREADS 5void *myThread(void *arg){printf("Thread %d started\n", (unsigned int)arg);pthread_exit(arg);}int main(){int ret, i, status;pthread_t threadids[MAX_THREADS];for(i=0; i<MAX_THREADS; i++){ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);if(ret!=0)printf("error creating thread %d\n", i);}for(i=0; i<MAX_THREADS; i++){ret=pthread_join(threadids[i], (void** )&status);if(ret!=0)printf("error joining thread %d\n", i);elseprintf("status=%d\n",status);}return 0;}為什么運行結果為:Thread 3 startedThread 4 startedThread 2 startedThread 1 startedThread 0 startedstatus=0status=1status=2status=3status=4謝謝!
2 回答

皈依舞
TA貢獻1851條經驗 獲得超3個贊
Linux系統pthread_join用于掛起當前線程(調用pthread_join的線程),直到thread指定的線程終止運行為止,當前線程才繼續執行。
案例代碼:
/******************************************* ** Name:pthread_join.c ** 用于Linux下多線程學習 ** 案例解釋線程的暫停和結束 ** Author:admin ** Date:2015/8/11 ** Copyright (c) 2015,All Rights Reserved! ********************************************** #include <pthread.h> #include <unistd.h> #include <stdio.h> void * thread ( void *str) { int i; //不調用pthread_join線程函數 for (i = 0; i < 10; ++i) { sleep(2); printf ( "This in the thread : %d\n" , i ); } return NULL; } int main() { pthread_t pth; int i; int ret = pthread_create(&pth, NULL, thread , ( void *)(i)); //調用pthread_join線程函數 pthread_join(pth, NULL); for (i = 0; i < 10; ++i) { sleep(1); printf ( "This in the main : %d\n" , i ); } return 0; } |
通過Linux下shell命令執行上面的案例代碼:
[root@localhost src] # gcc pthread_join.c -lpthread [root@localhost src] # ./a.out This in the main : 0 This in the thread : 0 This in the main : 1 This in the main : 2 This in the thread : 1 This in the main : 3 This in the main : 4 This in the thread : 2 This in the main : 5 This in the main : 6 This in the thread : 3 This in the main : 7 This in the main : 8 This in the thread : 4 This in the main : 9 |
子線程還沒有執行完畢,main函數已經退出,那么子線程也就退出了,“pthread_join(pth, NULL);”函數起作用。
[root@localhost src] # gcc pthread_join.c -lpthread [root@localhost src] # ./a.out This in the thread : 0 This in the thread : 1 This in the thread : 2 This in the thread : 3 This in the thread : 4 This in the thread : 5 This in the thread : 6 This in the thread : 7 This in the thread : 8 This in the thread : 9 This in the main : 0 This in the main : 1 This in the main : 2 This in the main : 3 This in the main : 4 This in the main : 5 This in the main : 6 This in the main : 7 This in the main : 8 This in the main : 9 |
這說明pthread_join函數的調用者在等待子線程退出后才繼續執行。

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
這是隨機情況,由系統調度決定,不是唯一的結果,你可以嘗試這樣改:ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);
sleep(1);
這樣就是按順序創建線程
- 2 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消