Search code examples
c++posix

Why do I need to use `pthread_exit()` from the main thread, while it was not created by a `pthread_create`?


I have a question about some code I'm testing to start understanding posix threads.

I have this basic code:

#include <iostream>
#include <string>
#include <sstream>
#include <pthread.h>

using namespace std;

void *printInfo(void *thid){
    long tid;
    tid =(long)thid;
    printf("Hello from thread %ld.\n",tid);
    pthread_exit(NULL);
}

int main (int argc, char const *argv[])
{
    int num =8;
    pthread_t threadlist[num];
    int rc;
    long t;
    for(t=0;t<num;t++){
        printf("Starting thread %ld\n",t);
        rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t);
        if(rc)
        {
            printf("Error creating thread");
            exit(-1);
            
        }
    }
    pthread_exit(NULL);
    return 0;
}

Very simple code, start threads and print from them, this all works wonders, except that I don't understand the last pthread_exit(NULL) before the return 0; in the end of the main method.

It seems that the main thread should not be a pthread, and should not need that! If I don't put it, the code does not work: the code compiles and executes, but I only get the "starting thread" print messages, and not the "hello from ..." messages.

So basically I want to know why is that needed.

Also, the code compiles and executes properly if I comment out the include <psthread.h>.


Solution

  • If you don't use pthread_exit in the main function then all created threads are terminated as main finishes, i.e. in your case before they have printed anything.

    By calling pthread_exit in the main function makes main wait until all threads have completed.

    From the pthread_exit man page:

    The process will exit with an exit status of 0 after the last thread has been terminated. The behavior is as if the implementation called exit() with a zero argument at thread termination time.

    This is referring to calling pthread_exit() from the main processes thread.