0

Why do we use pthread_exit(NULL) method in main() method when creating threads?

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

void *message(void *arg){
    char *myMessage = (char*)arg;
    printf("%s\n", myMessage);
}

int main(void){

   pthread_t arr[2];
   char *messages[2] = {"Hello", " World"};

   if( pthread_create(&arr[0], NULL, message, &messages[0]) != 0 ){
       printf("Creating thread failed");
   }

   if( pthread_create(&arr[1], NULL, message, &messages[1]) != 0 ){
       printf("Creating thread failed");
   }

   pthread_exit(NULL); -> WHY
}
2

This is documented in the pthread_exit(3) manpage:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

Basically, when you start threads, the current execution “context” is also a thread. The new threads have a life-cycle which might not be related to the main thread’s; so you need to end your main function with pthread_exit(), otherwise you’ll end up calling exit() (that’s what happens after you return from main), and that will stop all the process’ threads.

At the end of main, you don’t care about providing a return value to any other thread, hence the use of NULL as argument to pthread_exit().

| improve this answer | |
1

From man pthread_exit:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

From that, I'd conclude that exit() (or simply returning from main) will terminate the process (and all other threads) immediately, while calling pthread_exit() will hold off on process termination until the other threads finish their work.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.