multithread: why main thread exit leads to other threads exit?

In linux multithread program, when main thread exit, other threads will exit too, why? How to keep other thread running when main thread exit?

Consider following program, when main thread exit, new thread exit too. Why? C compiler insert a exit() after main(), so after main(), exit() will run. exit() will call group_exit() system call which terminate all threads of current process.

why other thread exit will not cause main thread exit? Other thread may exit by 1) return from its start function or 2) call pthread_exit(), either way it will call _exit() system call which only terminate its own.

so how to keep other thread running when main thread exit? let main thread exit using pthread_exit(). uncomment pthread_exit() in following program will produce the 2nd output.

questions:

what's detached state for a thread? Will it affect thread exit? The short answer is detached state only affects when OS reclaim thread's resources (like data structure used to represent thread), so has no effect to when thread exit. See blog for details.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

pthread_t ntid;

void printids(const char *s)
{
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
        (unsigned long)tid, (unsigned long)tid);
}
void *thr_fn(void *arg)
{
    int i;

    for (i = 0; i < 5; i++) {
        printids("new thread: ");
        sleep(1);
    }
    
    return((void *)0);
}

int main(void)
{
    int err;
    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if (err != 0) {
        printf("can’t create thread\n");
        exit(1);
    }
    printids("main thread:");
    sleep(1);
    //pthread_exit(0);
    //exit(0);
}

// output for upper program, new thread exit after main thread exit
$ ./a.out 
main thread: pid 30847 tid 140162470979392 (0x7f7a1e4b2740)
new thread:  pid 30847 tid 140162462480128 (0x7f7a1dc97700)
$

// output if pthread_exit(0) is used in main thread
// new thread keep running after main thread exit
$ ./a.out 
main thread: pid 30906 tid 140077780535104 (0x7f6666598740)
new thread:  pid 30906 tid 140077772035840 (0x7f6665d7d700)
new thread:  pid 30906 tid 140077772035840 (0x7f6665d7d700)
new thread:  pid 30906 tid 140077772035840 (0x7f6665d7d700)
new thread:  pid 30906 tid 140077772035840 (0x7f6665d7d700)
new thread:  pid 30906 tid 140077772035840 (0x7f6665d7d700)
$

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值