Mihai Neacsu
Mihai Neacsu

Reputation: 2095

Second detached thread doesn't print messages

Trying to set up a small client-server program. However, I've noticed output from the second thread doesn't get out printed.

void *ClientRoutine(void *args){
    printf("Client thread created\n");

    pthread_exit(NULL);
}

int main(int argc, char *argv[]){
    pthread_t client_thread;
    pthread_attr_t attr;

     pthread_attr_init(&attr);
     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    if (pthread_create(&client_thread, &attr, &ClientRoutine, NULL)) {
        perror("Failed to create client thread");
        exit(-1);
    }

    pthread_attr_destroy(&attr);

    return 0;
}

If I printf something in the main thread, the client's output finally shows up. Can anyone explain why this is happening?

LE: as some of you have suggested, this does happen because the main thread exits early. However, according to this: What happens to a detached thread when main() exits?, the detached thread should continue execution even after main exits. Why does this happen?

Upvotes: 1

Views: 1128

Answers (2)

Seema Kadavan
Seema Kadavan

Reputation: 2638

This might happen when your main thread exits before the newly created one gets time to print. Can be solved if the main thread waits till the other thread has completed the action. Use pthread_join for this.

Try calling

pthread_join(client_thread, NULL);

before

pthread_attr_destroy(&attr);

When you add another print statement in main thread, it actually keeps the main thread alive for more duration.

Upvotes: 0

Diego Sevilla
Diego Sevilla

Reputation: 29021

Maybe you're destryoing the detached thread too early? If you just create the thread and then destroy it, you don't give printf even time to execute. Try to add some sleep time after the thread creation in main and you'll see the output.

When you add another printf in the main thread, you give the other thread time to execute before being destroyed.

Upvotes: 1

Related Questions