Linux 多线程编程

/*************************************************************************
	> 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(等待线程退出);运行结果:函数

thread1.png

首先,建立三个线程,主线程分别用pthread_join等待其退出,由于pthread_join是阻塞等待,从而也就有前后顺序,从打印结果就能够看出;线程

二、当没有定义THREAD宏,没有定义JOINblog

建立三个线程,后面加sleep;运行结果:进程

thread2.png

首先,建立三个线程,主线程没有用pthread_join等待其退出;若是没有加sleep,结果是:内存

8sd7f897s89df7.png

由于建立了线程,根本没有时间执行,为啥呢?(由于主线程(进程)执行完退出了,从而处处全部线程结束,没有时间执行)。资源

因此主线程要sleep几秒,让你建立的线程有机会执行;并且你能够看到,没有用pthread_join等待时,线程执行顺序是不肯定的。it

你还能够发现,线程三的执行函数是一个while,这里只打印了2句while里的函数,由于用了pthread_cancel(取消线程);后面的sleep10全部的线程都退出了可是资源没有释放(占空间)为啥这样说呢?看下面:io

三、当定义了THREAD宏class

这时,主线程是一个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的堆栈,因此当你没有释放资源时,空间确定不够用,从而致使失败。(不是建立全部线程都失败,而是到那个最大值时出错的而失败的)

相关文章
相关标签/搜索