【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;
}

🎄三

🎄四

🎄五

🎄六、

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

相关推荐
xbd_zc2 小时前
【Vagrant+VirtualBox创建自动化虚拟环境】Ansible测试Playbook
linux·ubuntu·自动化·ansible·虚拟机·vagrant·virtualbox
Mr_Chenph3 小时前
真.从“零”搞 VSCode+STM32CubeMx+C <2>调试+烧录
c语言·stm32·嵌入式硬件
YuforiaCode3 小时前
第十六届蓝桥杯 2025 C/C++B组第一轮省赛 全部题解(未完结)
c语言·c++·蓝桥杯
lsnm3 小时前
【LINUX操作系统】线程操作
linux·jvm·c++·ubuntu·centos·gnu
FREEDOM_X4 小时前
Ubuntu 20.04 安装 ROS 2 Foxy Fitzroy
linux·ubuntu·机器人
华纳云IDC服务商4 小时前
如何利用Rust提升Linux服务器效率(详细操作指南)
linux·服务器·rust
Darkwanderor4 小时前
c语言的常用的预处理指令和条件编译
c语言
桦05 小时前
【Linux】g++安装教程
linux·运维·服务器
bai_lan_ya5 小时前
C语言中结构体的字节对齐的应用
c语言·开发语言
海阔天空任鸟飞~5 小时前
杰理-安卓通过map获取时间的时候,部分手机切换sbc和aac时候单耳无声音
c语言·单片机·aac