Linux中主子线程的退出顺序


  1. 主线程和子线程之间没有必然的退出次序关系。主线程退出,子线程可以继续执行;子线程退出,主线程也可以继续执行。
  2. 程序加载到内存中执行的时候,进程就会生成一个主线程。虽然主线程和子线程之间没有必然的退出次序关系,但是如果进程终止,那么进程下所有的线程都会终止。

子线程先终止,主线程后终止

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
 
void printids(const char *str) {
    pid_t pid = getpid();
    pthread_t tid = pthread_self();
    printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
 
void *func(void *arg) {
    printids("descendant thread");
    pthread_detach(pthread_self());
    return ((void*)0);
}
 
int main(void) {
    pthread_t myid;
    pthread_create(&myid, NULL, func, NULL);
    
    sleep(1);  // 等待子线程先退出
    printids("main thread");
 
    return 0;
}

进程结束,所有线程都终止

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
 
void printids(const char *str) {
    pid_t pid = getpid();
    pthread_t tid = pthread_self();
    printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
 
void *func(void *arg) {
    sleep(1);  // 等待主线程先退出
    printids("descendant thread");
    pthread_detach(pthread_self());
    return ((void*)0);
}
 
int main(void) {
    pthread_t myid;
    pthread_create(&myid, NULL, func, NULL);
    
    // sleep(1);  // 等待子线程先退出
    printids("main thread");
 
    return 0;  //进程退出,系统清除所有资源
}

进程结束,子线程部分来不及执行


主线程先终止,子线程后终止

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
 
void printids(const char *str) {
    pid_t pid = getpid();
    pthread_t tid = pthread_self();
    printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
 
void *func(void *arg) {
    sleep(1);  // 等待主线程先退出
    printids("descendant thread");
    pthread_detach(pthread_self());
    return ((void*)0);
}
 
int main(void) {
    pthread_t myid;
    pthread_create(&myid, NULL, func, NULL);
    
    printids("main thread");
    pthread_exit(NULL);
 
    return 0;  //进程退出,系统清除所有资源
}

当主线程在子线程终止之前调用pthread_exit()时,子线程是不会退出的。

注意:这里在main函数中调用pthread_exit()只会是主线程退出,而进程并未退出。参照CSAPP中的讲解,当主线程执行pthread_exit()之后,主线程终止,进程并未终止,而是等待所有的子线程终止之后再结束。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VioletEvergarden丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值