4 Thread joining in Linux
4 Thread joining in Linux
Program which contain in the post this and this main doesnt wait for thread finishes their work.
We can make the main thread wait for the child thread to finish their work with the help of thread join mechanism.
We need to set thread as joinable by using thread attribute.
API used for thread join :
int pthread_attr_init(pthread_attr_t *attr);This API used to init thread attribute. Pass pthread_attr_t type variable as argument.
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);Here only we need to set the properties of attribute variable. First argument is pthread_attr_t type variable and second argument is state.
There is two type of state
- PTHREAD_CREATE_DETACHED - Threads that are created using attr will be created in a detached state.
- PTHREAD_CREATE_JOINABLE - Threads that are created using attr will be created in a join? able state
int pthread_attr_destroy(pthread_attr_t *attr);
Once thread finishes the use of attribute we can remove the help of pthread_attr_destroy.
int pthread_join(pthread_t thread, void **retval);
This used to join with terminated thread. When thread routine meet the pthread_exit(NULL) it will give the status to pthread_join APIs second argument.
If thread exited normally then pthread_join will get 0 as return value in second argument.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *t_function(void*);
void *t_function(void* arg) //thread handler
{
int t_num = (int)arg;
int x = 0;
printf("thread created and running ");
printf("thread argument : %d ", t_num);
while (x != 10){
sleep(1);
x++;
}
printf("thread finishes the work ");
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t mythread;
pthread_attr_t myattr;
void *joinResult;
int x = 0;
int t_arg = 1;
pthread_attr_init(&myattr);
pthread_attr_setdetachstate(&myattr, PTHREAD_CREATE_JOINABLE);
if((pthread_create(&mythread, &myattr, t_function, (void*)t_arg) != 0)){
printf("Error, thread not created properly ");
exit(-1);
}
while(x != 5){
sleep(1);
x++;
}
pthread_attr_destroy(&myattr);
if(pthread_join(mythread, &joinResult) != 0 ){
printf("Error pthread join ");
return 1;
}
printf("Main : joined with result of %d ", (int)joinResult);
printf("main finishes the work ");
pthread_exit(NULL);
}
OUTPUT :
thread created and running
thread argument : 1
thread finishes the work
Main : joined with result of 0
main finishes the work
Program Explanation :
- Create mythread and myattr variable.
- Initialize attribute with the help of pthread_attr_init
- Set thread join-able with the help of pthread_attr_setdetachstate
- Create thread using pthread_create by passing attribute arguments
- Remove the attribute after thread create
- With the help of pthread_join make main in waiting till thread finishes the work
Comments
Post a Comment