1. 程式人生 > >Linux 多線程編程

Linux 多線程編程

malloc 比較 images id3 while 釋放資源 出了 分享 不用

/************************************************************************* > File Name: pthread.c > Author: zhaoxiaohu > Mail: [email protected] > Created Time: Sat 21 Jul 2018 11:40:55 AM CST ************************************************************************/ #include<stdio.h> #include<pthread.h> #include<stdlib.h> //#define THREAD #define JOIN void *thread1(void *arg) { pthread_detach(pthread_self()); int arr[1024] = {0}; printf("thread 1 is running go return\n"); return 1; } void *thread2(void *arg) { printf("thread 2 is running go exit\n"); pthread_exit((void *)5); } void *thread3(void *arg) { while(1){ sleep(1); printf("thread 3 is running wait exit\n"); } return NULL; } int main() { pthread_t tid1; #ifdef THREAD while(1) { if(!pthread_create(&tid1,NULL,thread1,NULL)) { //pthread_join(tid1,NULL); printf("create ok!!!\n"); } else printf("create error!!!\n"); } #else pthread_t tid2; pthread_t tid3; void *retval; pthread_create(&tid1,NULL,thread1,NULL);//創建線程 #ifdef JOIN pthread_join(tid1,&retval); #endif pthread_create(&tid2,NULL,thread2,NULL); #ifdef JOIN pthread_join(tid2,&retval); printf("retval = %d\n",(int)retval); #endif pthread_create(&tid3,NULL,thread3,NULL); #ifdef JOIN pthread_join(tid3,&retval); #endif printf("i am main thread tid1 = %u,tid2 = %u,tid3 = %u\n", (unsigned long) tid1,(unsigned long) tid2,(unsigned long) tid3); sleep(3); pthread_cancel(tid3); sleep(10); #endif return 0; }

1、當沒有定義THREAD宏,定義JOIN

創建三個線程,每個線程都通過pthread_join(等待線程退出);運行結果:

技術分享圖片

首先,創建三個線程,主線程分別用pthread_join等待其退出,因為pthread_join是阻塞等待,從而也就有先後順序,從打印結果就可以看出;

2、當沒有定義THREAD宏,沒有定義JOIN

創建三個線程,後面加sleep;運行結果:

技術分享圖片

首先,創建三個線程,主線程沒有用pthread_join等待其退出;如果沒有加sleep,結果是:

技術分享圖片

因為創建了線程,根本沒有時間執行,為啥呢?(因為主線程(進程)執行完退出了,從而到處所有線程結束,沒有時間執行)。

所以主線程要sleep幾秒,讓你創建的線程有機會執行;而且你可以看到,沒有用pthread_join等待時,線程執行順序是不確定的。

你還可以發現,線程三的執行函數是一個while,這裏只打印了2句while裏的函數,因為用了pthread_cancel(取消線程);後面的sleep10所有的線程都退出了但是資源沒有釋放(占空間)為啥這樣說呢?看下面:

3、當定義了THREAD宏

這時,主線程是一個while 去創建線程

1)當線程執行函數中有pthread_detach(線程分離),此時線程資源自動釋放,結果:

技術分享圖片

2)當主線程用pthread_join(等待線程退出),此時結果:

技術分享圖片

比較1)和2),一個自動釋放資源不用主線程幹預,一個主線程join,然後釋放資源,而且可以看到join表現了阻塞和執行順序。

3)當線程執行函數沒有pthread_detach(線程分離)和主線程沒有pthread_join(等待線程結束),運行結果:

技術分享圖片

*為什麽會出現create error;因為創建的線程有一個最大數,為啥呢:

一個程序到一個進程,從磁盤到虛擬內存的映射,而虛擬內存是有限的,32位,4g;而且1g個內核用了,所以用戶只能使用3g,3g包含了代碼段,數據段,堆棧,malloc的空間等,所以空間是有限;而每創建一個線程,默認分配8M的堆棧,所以當你沒有釋放資源時,空間肯定不夠用,從而導致失敗。(不是創建所有線程都失敗,而是到那個最大值時出錯的而失敗的)


Linux 多線程編程