Search code examples
linuxprocesspthread-join

Questions on pthread_join() and pthread_create()


This is the declaration of pthread_create:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *  
          (*start_routine) (void *), void *arg);

it contains a function start_routine.

So when we call pthread_create, the function will execute with param arg.
Then why is it necessary to call pthread_join() since the start_routine function is to be execute?
I also tried not to include pthread_join() function, indeed the start_routine function is not executed at all and the process just exit after being created.
So when the programm comes to pthread_create, what exactly will it go on? The execution of the param start_routine is conditional or not?
Confusing... Here are my test code:

#include <pthread.h>
#include <stdio.h>
int sum;
void* runner(void *param);

int main(int argc, char *argv[])
{
    pthread_t tid; //The thread identifier
    pthread_attr_t attr;//set of thread attributes

    if(argc!=2){
    fprintf(stderr, "usage:a.out <integer value>\n");
    return -1;
    }
    if(atoi(argv[1])<0){
    fprintf(stderr, "%d must be <=0\n",atoi(argv[1]));
    return -1;
    }


    //get the default attributes
    pthread_attr_init(&attr);
    //create the thread
    pthread_create(&tid,&attr,runner,argv[1]);
    //now wait for the thread to exit
    pthread_join(tid,NULL);

    printf("sum=%d\n", sum);
}

    void* runner(void *param)
    {
        int i,upper = atoi(param);
        sum=0;

        for(i=1;i<=upper;i++)
            sum+=i;

        pthread_exit(0);
    }

Solution

    1. Usually, your routine will be called. And if it doesn't have anything to do and exits, your thread life is complete.
    2. Does your start_routine() have any code/print statements by which you can verify/debug its functionality?
    3. Calling pthread_join() is not necessary. It will be required if you want to wait for the start_routine() after it finishes/terminates its execution (internally/externally). And check the return status of the thread function.
    4. Other scenario for the thread not to run could be: system is very low of memory OR the existing threads (and their priorities) is hogging the system so much that it doesn't get any chance to run.
    5. Did you also check the error code from pthread_create()?

    It will help if you can share your test code including the caller of pthread_create() and the start_routine().