Linux 多線程編程

/*************************************************************************
	> 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(等待線程退出);運行結果:

thread1.png

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

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

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

thread2.png

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

8sd7f897s89df7.png

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

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

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

3、當定義了THREAD宏

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

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

thread_detach.png

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

join.png

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

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

no_join.png

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

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章