Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c - pthread_detach question

Till recently, I was under the impression that if you "detach" a thread after spawning it, the thread lives even after the "main" thread terminates.

But a little experiment (listed below) goes contrary to my belief. I expected the detached thread to keep printing "Speaking from the detached thread" even after main terminated, but this does not seem to be happening. The application apparently terminates...

Do the "detached" threads die after "main" issues return 0?

#include <pthread.h>
#include <stdio.h>

void *func(void *data)
{
    while (1)
    {
        printf("Speaking from the detached thread...
");
        sleep(5);
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t handle;
    if (!pthread_create(&handle, NULL, func, NULL))
    {
        printf("Thread create successfully !!!
");
        if ( ! pthread_detach(handle) )
            printf("Thread detached successfully !!!
");
    }

    sleep(5);
    printf("Main thread dying...
");
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To quote the Linux Programmer's Manual:

The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).

Also from the Linux Programmer's Manual:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...