/************************************************************************* > File Name: pthread.c > Author: zhaoxiaohu > Mail: 191711783@qq.com > 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; }
一、當沒有定義THREAD宏,定義JOINide
建立三個線程,每一個線程都經過pthread_join(等待線程退出);運行結果:函數
首先,建立三個線程,主線程分別用pthread_join等待其退出,由於pthread_join是阻塞等待,從而也就有前後順序,從打印結果就能夠看出;線程
二、當沒有定義THREAD宏,沒有定義JOINblog
建立三個線程,後面加sleep;運行結果:進程
首先,建立三個線程,主線程沒有用pthread_join等待其退出;若是沒有加sleep,結果是:內存
由於建立了線程,根本沒有時間執行,爲啥呢?(由於主線程(進程)執行完退出了,從而處處全部線程結束,沒有時間執行)。資源
因此主線程要sleep幾秒,讓你建立的線程有機會執行;並且你能夠看到,沒有用pthread_join等待時,線程執行順序是不肯定的。it
你還能夠發現,線程三的執行函數是一個while,這裏只打印了2句while裏的函數,由於用了pthread_cancel(取消線程);後面的sleep10全部的線程都退出了可是資源沒有釋放(佔空間)爲啥這樣說呢?看下面:io
三、當定義了THREAD宏class
這時,主線程是一個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的堆棧,因此當你沒有釋放資源時,空間確定不夠用,從而致使失敗。(不是建立全部線程都失敗,而是到那個最大值時出錯的而失敗的)