【Linux C | 多线程编程】线程的退出

😁博客主页😁:🚀https://blog.csdn.net/wkd_007🚀
🤑博客内容🤑:🍭嵌入式开发、Linux、C语言、C++、数据结构、音视频🍭
⏰发布时间⏰:

本文未经允许,不得转发!!!

目录


🎄一、概述

本文主要介绍线程退出的几种方式,以及各种方式之间的区别

✨1.1

✨1.2

🎄二、线程会终止, 进程不会终止 的三种方式

下面的三种方法中,线程会终止,但是进程不会终止(如果线程不是进程组里的最后一个线程的话):

  • 创建线程时的 start_routine 函数执行了return, 并且返回指定值。
  • 线程调用 pthread_exit
  • 其他线程调用了 pthread_cancel 函数取消了该线程。

例子一:线程函数使用 return 终止线程

c 复制代码
// 06_pthread_return.c
// gcc 06_pthread_return.c -l pthread
#include <stdio.h>
#include <pthread.h>
void *func(void *arg)
{
	int *parg = arg;
	printf("this thread arg is %d, my threadID is %lx \n", *parg, (unsigned long)pthread_self());
	return NULL;
}
int main()
{
	int arg=10;
	pthread_t threadId;
	pthread_create(&threadId, NULL, func, &arg);
	return 0;
}

例子二:线程函数使用 pthread_exit 终止线程

c 复制代码
// 06_pthread_exit.c
// gcc 06_pthread_exit.c -l pthread
#include <stdio.h>
#include <pthread.h>
void *func(void *arg)
{
	int *parg = arg;
	printf("this thread arg is %d, my threadID is %lx \n", *parg, (unsigned long)pthread_self());
	pthread_exit(NULL);
}

int main()
{
	int arg=10;
	pthread_t threadId;
	pthread_create(&threadId, NULL, func, &arg);
	return 0;
}

🎄三

🎄四

🎄五

🎄六、

如果文章有帮助的话,点赞👍、收藏⭐,支持一波,谢谢 😁😁😁

相关推荐
藥瓿锻10 分钟前
2024 CKA题库+详尽解析| 15、备份还原Etcd
linux·运维·数据库·docker·容器·kubernetes·cka
bbsh209919 分钟前
WebFuture:Ubuntu 系统上在线安装.NET Core 8 的步骤
linux·ubuntu·.netcore·webfuture
ZZZKKKRTSAE28 分钟前
快速上手Linux全局搜索正则表达式(grep)
linux·服务器·正则表达式
waving-black2 小时前
利用frp和腾讯云服务器将内网暴露至外网(内网穿透)
linux·服务器·腾讯云·frp·内网穿透
stormsha2 小时前
Linux中su与sudo命令的区别:权限管理的关键差异解析
linux·运维·服务器·鸿蒙系统·ux·batch命令
草莓熊Lotso2 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM2 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
筏.k3 小时前
grep、wc 与管道符快速上手指南
linux
Johny_Zhao3 小时前
华为MAAS、阿里云PAI、亚马逊AWS SageMaker、微软Azure ML各大模型深度分析对比
linux·人工智能·ai·信息安全·云计算·系统运维
CodeOfCC3 小时前
c语言 封装跨平台线程头文件
linux·c语言·windows