Linux系统编程_课时71_线程退出函数pthread_exit(void* retval)

课时71_线程退出函数pthread_exit(void* retval)

1、函数原型:

void pthread_exit(void* retval)
retval指针:如果需要传递指针,必须指向全局、堆,不能指向栈。

2、主线程使用pthread_exit退出不影响子线程运行

2.1、代码示例

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h> //线程对应的头文件

//回调函数,子线程要做的任务
void* myfun(void* arg)
{
	//打印子线程的ID
	printf("child thread id:%ld\n",pthread_self());
	int i=0;
	while(1)
	{
		printf("child i=%d\n",i++);
	}
	return NULL;
}

//主函数
int main()
{
	//创建一个子线程
	pthread_t	pthid;
	int ret = pthread_create(&pthid,NULL,myfun,NULL);
	if(ret != 0)
	{
		printf("err number:%d\n",ret);
		//打印错误信息,使用strerror函数
		printf("%s\n",strerror(ret));
	}

	//打印父线程ID
	printf("parent thread id:%ld\n",pthread_self());

	//退出主线程,不影响子线程,使用pthread_exit函数
	pthread_exit(NULL);
	printf("after parent thread exit\n");
	return 0;
}

2.1、执行结果:

主线程使用pthread_exit函数退出线程后,子线程依然正常运行。

root@Ubuntu18:/home/remotefs/001.Linux_sys#
root@Ubuntu18:/home/remotefs/001.Linux_sys# ./a.out
parent thread id:140101890004800
child thread id:140101881489152
child i=0
child i=1
child i=2
child i=3
child i=4
child i=5
child i=6

3、子线程使用exit()退出影响主线程运行

子线程使用exit()函数退出,父进程的地址空间也同时被释放。

3.1、代码示例

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h> //线程对应的头文件

//回调函数,子线程要做的任务
void* myfun(void* arg)
{
	//打印子线程的ID
	printf("child thread id:%ld\n",pthread_self());
	for(int i=0;i<5;i++)
	{
		printf("child i=%d\n",i);
		if(i==2)
		{
			exit(1);
		}
	}
	return NULL;
}

//主函数
int main()
{
	//创建一个子线程
	pthread_t	pthid;
	int ret = pthread_create(&pthid,NULL,myfun,NULL);
	if(ret != 0)
	{
		printf("err number:%d\n",ret);
		//打印错误信息,使用strerror函数
		printf("%s\n",strerror(ret));
	}

	//打印父线程ID
	printf("parent thread id:%ld\n",pthread_self());
	int i=0;
	while(1)
	{
		printf("parent i=%d\n",i++);
	}
	return 0;
}

3.2、执行结果:

子线程运行到i==2后使用exit()函数退出,主线程也被强制结束。

parent i=3064
parent i=3065
parent i=3066
parent i=3067
parent i=3068
parent i=3069
parent i=3070
parent i=3071
parent i=3072
child thread id:140498387150592
child i=0
child i=1
child i=2
root@Ubuntu18:/home/remotefs/001.Linux_sys#
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值