thread7 进程结束时机

来源:互联网 发布:c语言ceil 编辑:程序博客网 时间:2024/06/07 01:41
线程结束时机:
执行到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]# ./thread5main thread will exit !thread_function is running. Argument was Hello Worldsub thread will exit ![root@localhost ch12]# 
可以看出all exit!没有打印出来,main线程确实是被结束掉了
,但子线程仍在执行,并且子线程函数执行完毕时,子线程结束,进程也变结束


原创粉丝点击