0

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?

Community
  • 1
  • 1
Mihai Neacsu
  • 2,045
  • 5
  • 23
  • 37
  • 1
    You're refering in the latter statement to C++. One thing is that the C++ standard doesn't state it clearly. Another thing is OS handling threads and processes. When a process exists, all its threads (detached or not) are deleted. – Diego Sevilla Apr 22 '15 at 10:17

2 Answers2

1

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.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
  • Fair enough, Diego! It does work with sleep. But I thought the detached thread continues execution even after main ends, at least according to this: http://stackoverflow.com/questions/19744250/c11-what-happens-to-a-detached-thread-when-main-exits – Mihai Neacsu Apr 22 '15 at 10:08
  • 1
    Look at this answer: http://stackoverflow.com/a/6043018/62365 . When the "process" ends (via `exit()`), all the threads end, even detached ones. If you call `pthread_exit()` on the main thread, then the other thread will continue, but again, the program itself is still running. If you want to detach just a thread that continue execution, I think you'll better create a `fork()`. – Diego Sevilla Apr 22 '15 at 10:14
0

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.

Seema Kadavan
  • 2,538
  • 1
  • 16
  • 31