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...\n");
        sleep(5);
    }
    pthread_exit(NULL);
}

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

    sleep(5);
    printf("Main thread dying...\n");
    return 0;
}
20
задан puffadder 18 May 2011 в 10:06
поделиться