Tuesday, August 13, 2013

Thread Join In C

Why thread Join??
As we have seen in the first multithreaded program that we have the while(1) loop in the main function ,that is to ensure that the application/program keeps runnning because if main ends the program ends...
Now if we dun want to waste the time in the main program and only want to run the threads we can use the thread join to achieve this task.

what is a join??
Join means we are telling the thread to join with the other thread that is we are telling that wait for the other thread to finish..
So two threads are included in the join
first thread -to whom we are saying to join
second thread-the thread to join with
suppose there is Thread1 and Thread2,and we require the Thread2 must complete before Thread1 so we have to tell the Thread1 to join with the Thread2..
So in our Example,We have to say main to join with the Thread1 and Thread2 ,that is telling main to wait for both the Threads to complete,
So, By using join we need not to worry about the main,the main will end only after the completion of the both threads..


Funtion prototype:
int pthread_join(pthread_t tid, void **status);
The first argument is the thread ID.
The second argument is a pointer to the data your thread function returned,keep it as NULL for now.

Example:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void* myfunc1(void *ptr)
{
    char *msg;
    int i=0;
    msg= (char*)ptr;
    while(1)
    {
        printf("In the %s\n",msg);
        sleep(1);
    if(i++> 7)
    break;
    }
printf("Thread1 completed\n");
}
void *myfunc2(void *ptr)
{
    char *msg;
    int i=0;
    msg= (char*)ptr;
    while(1)
    {
        printf("In the %s\n",msg);
        sleep(1);
    if(i++>10 )
    break;
    }
printf("Thread2 completed\n");
}
int main()
{
    pthread_t thread1,thread2;
    int val1,val2;
    int status;
    char *msg1="Thread1";
    char *msg2="Thread2";
    void **ret_val;
    printf("In the main funciton\n");
    val1=pthread_create(&thread1,NULL,myfunc1,(void*)msg1);
    val2=pthread_create(&thread2,NULL,myfunc2,(void*)msg2);
    printf("the value returned by thread1=%d\n",val1);
    printf("the value returned by thread2=%d\n",val2);
    pthread_join(thread1,NULL);//telling main to join with thread1
    pthread_join(thread2,NULL);//telling main to join with thread2
        printf("Now main ends:\n");
    return 0;
}