代碼如下:#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.outThis in the main : 0This in the thread : 0This in the main : 1This in the main : 2This in the thread : 1This in the main : 3This in the main : 4This in the thread : 2This in the main : 5This in the main : 6This in the thread : 3This in the main : 7This in the main : 8This in the thread : 4This in the main : 9 |
子線程還沒有執行完畢,main函數已經退出,那么子線程也就退出了,“pthread_join(pth, NULL);”函數起作用。
[root@localhost src]# gcc pthread_join.c -lpthread[root@localhost src]# ./a.outThis in the thread : 0This in the thread : 1This in the thread : 2This in the thread : 3This in the thread : 4This in the thread : 5This in the thread : 6This in the thread : 7This in the thread : 8This in the thread : 9This in the main : 0This in the main : 1This in the main : 2This in the main : 3This in the main : 4This in the main : 5This in the main : 6This in the main : 7This in the main : 8This in the main : 9 |
這說明pthread_join函數的調用者在等待子線程退出后才繼續執行。
呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
這是隨機情況,由系統調度決定,不是唯一的結果,你可以嘗試這樣改:ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);
sleep(1);
這樣就是按順序創建線程
- 2 回答
- 0 關注
- 132 瀏覽
添加回答
舉報
0/150
提交
取消
