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)
$

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章