Question

Having this piece of code:

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

void* PrintHello(void* data){

        printf("Hello from new thread\n");
        pthread_exit(NULL);

}

int main(int argc, char* argv[]){
    int rc;
    pthread_t thread_id;
    T_DATA data;

    Data = init_data();
    rc = pthread_create(&thread_id, NULL, PrintHello, (void*)data);
    if(rc){
        printf("\n ERROR: return code from pthread_create is %d \n", rc);
        exit(1);
    }
    sleep(100);
    printf("\n Created new thread (%d) ... \n", thread_id);
    pthread_join(thread_id);
}

When main creates the new thread and then perform sleep(100), the new thread probably reach pthread_exit before main reach pthread_join. Anyways the new thread waits and his resources are not freed until main perform pthread_join so if i execute ps command i will see the new thread during next 100 seconds, am i right?. I would get the same behavior if I use pthread_detach instead pthread_join? I wonder what happen when the new thread perform the pthread_exit before main perform pthread_detach over the thread.

Was it helpful?

Solution

The thread cannot be cleaned up until it terminates, of course. But it also cannot be cleaned up until it is either joined or detached. A thread that terminates without being detached will keep enough information around to allow another thread to join it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top