Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

Thread created (detached) never executed

I have written this code:

void* th (void* arg)
{
    sleep(1);
    for(int i=0; i<1000;i++)
    {
    fprintf(stderr,"%d\t",i);
    }
    pthread_exit(NULL);
}

int main(int argc, char** argv)
{
    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    pthread_create(&thread,&attr,th,NULL);
    pthread_attr_destroy(&attr);
    return 0;
}

The detach state should make the thread not joinable, so it should run even after the main process is terminated.But it doesn't print the numbers, all I see is that the thread terminated without printing anything to stderr.
Why isn't the detached thread executed?

Upvotes: 0

Views: 195

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78973

A return from the main thread is equivalent to an exit of the whole process, so your process will exit before your thread may even print anything. Use pthread_exit instead to terminate that thread.

Upvotes: 6

Related Questions