c線程中sleep()和pthread_join()函數之我見


線程之我見,有錯誤,請指正,謝謝

線程的執行需要cpu資源,而cpu的利用時各個線程進行“輪詢”即輪時間片,拋開優先級不說,一個線程如果執行的時候,分配給他的時間片到了,他就要交出cpu執行權,由其他等待cpu的線程來執行,(一個cpu一次只能執行一個線程)。

而sleep()的作用是讓當前執行cpu的線程掛起,交出cpu,讓其他等待cpu的線程執行,

測試程序:

 1 #include<stdio.h>
 2 #include<pthread.h>
 3 #include<stdlib.h>
 4 void *fun(void *p){
 5     int i=0;
 6     for(i;i<10;i++){
 7         printf("fun i=%d\n",i);
 8     }
 9     printf("fun bye bye\n");
10     return NULL;
11 }
12 int main(){
13     pthread_t th;
14     if(pthread_create(&th,NULL,fun,NULL)<0){//pthread_create()函數參數請百度
15         perror("pthread_create");
16         return -1;
17     }
18     printf("main bye bye\n");
19     return 0;
20 }

 

如果是上面程序的話,在主線程main中沒有sleep()和pthread_join()函數,猜一猜運行結果如何,

 

對,沒錯,只運行了主線程main,那么如果在main函數中加入sleep()函數的話(sleep參數不是0),那么是否是我們想要的結果呢?

測試程序:

 1 #include<stdio.h>
 2 #include<pthread.h>
 3 #include<stdlib.h>
 4 void *fun(void *p){
 5     int i=0;
 6     for(i;i<10;i++){
 7         printf("fun i=%d\n",i);
 8     }
 9     printf("fun bye bye\n");
10     return NULL;
11 }
12 int main(){
13     pthread_t th;
14     if(pthread_create(&th,NULL,fun,NULL)<0){//pthread_create()函數參數請百度
15         perror("pthread_create");
16         return -1;
17     }
18     sleep(1);//參數不為0
19     printf("main bye bye\n");
20     return 0;
21 }

運行結果:

果然是進入子線程fun中執行了,我猜操作系統是這樣運行的:先是main線程,執行,經過create子線程的時候,創造出來的線程是就緒態,在等待隊列中等待cpu的執行,現在還是main線程執行,在沒有sleep函數的時候,main執行到return 0程序末尾的時候,main結束了,釋放了空間,這時候子線程fun由main創造出來,主(進程)釋放掉空間了,所以他就沒法執行了;在main中有sleep函數的時候,main線程睡覺掛起了,把cpu交出來讓給其他等待執行的線程去了,這時候子線程fun得以執行,執行完了,返回到main中繼續執行。

由此猜想:如果他們都是在輪時間片的話,是否在main線程用光了時間片后會交出cpu執行權呢?

測試程序:

 1 #include<stdio.h>
 2 #include<pthread.h>
 3 #include<stdlib.h>
 4 int flag=1;//全局標志位
 5 void *fun(void *p){
 6     int i=0;
 7     for(i;i<10;i++){
 8         printf("fun i=%d\n",i);
 9     }
10     printf("fun bye bye\n");
11     flag=0;
12     return NULL;
13 }
14 int main(){
15     pthread_t th;
16     if(pthread_create(&th,NULL,fun,NULL)<0){//pthread_create()函數參數請百度
17         perror("pthread_create");
18         return -1;
19     }
20 //    sleep(1);//這次不用sleep函數,看是否main在用光了時間片后會交出時間片讓其他等待程序執行呢
21     int i=0;
22     while(flag){
23         printf("main i=%d\n",i++);
24     }
25     printf("main bye bye\n");
26     return 0;
27 }

運行結果:

正如我們所想,在main線程中執行while循環,等到時間片用完了后,交出cpu有等待隊列中的線程執行,然后fun執行完了,交給主線程main再執行。

總之:sleep函數的作用是讓本線程睡眠掛起,交出cpu資源,讓等待隊列中的處於就緒狀態的線程執行,在哪個線程中調用sleep就讓哪個線程睡眠掛起。

鄙人之愚見,錯誤請指正。謝謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM