thread7 进程结束时机

本文深入探讨了线程和进程的结束时机,包括线程通过pthread_exit()或执行到末尾结束,以及进程在任一线程执行exit()、主线程执行main函数末尾或所有线程结束时结束。通过实验展示了所有线程结束后的进程结束过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程结束时机:
执行到pthread_exit()函数时
执行到线程函数的最后一个}时
(但对主线程而言,执行到main函数的最后一个}时,编译器在此处放一个exit(),从而使进程结束,从而使所有线程结束)
what's more,
如果是子线程是分离的,则结束掉之后不会返回,自行消失
否则结束掉之后,可以用pthread_exit(argument),将结果返回至主线程中(主线程pthread_join)

进程结束时机:
任意一个线程执行exit()函数时
主线程执行到main函数的最后一个}时
所有线程都结束后(所有线程可以都用pthread_exi结束掉自己,主线程也不例外,主线程结束掉,子线程仍可运行)

针对"所有线程都结束后"de 一试验
[root@localhost ch12]# cat thread5.c 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function(void *arg);

char message[] = "Hello World";
int thread_finished = 0;
    int res;
int main() {
	int res;
	pthread_t a_thread;
	void *thread_result;

	res = pthread_create(&a_thread,NULL, thread_function, (void *)message);

	if (res != 0) {
	perror("Thread creation failed");
	exit(EXIT_FAILURE);
	}

	printf("main thread will exit !\n");
	pthread_exit(NULL);
	printf("all exit!\n");
	//exit(0);
}

void *thread_function(void *arg) {
	printf("thread_function is running. Argument was %s\n", (char *)arg);
	sleep(2);
	printf("sub thread will exit !\n");
	//pthread_exit(NULL);
}


[root@localhost ch12]# ./thread5
main thread will exit !
thread_function is running. Argument was Hello World
sub thread will exit !
[root@localhost ch12]# 
可以看出all exit!没有打印出来,main线程确实是被结束掉了
,但子线程仍在执行,并且子线程函数执行完毕时,子线程结束,进程也变结束


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值