The pthread_join function blocks the calling thread until the specified thread terminates.
Syntax
int pthread_join(thread_t tid, void **status);
- tid - The function blocks the calling thread, until the thread id specified in this terminates.
- status - When status is not NULL, status points to a location that is set to the exit status of the terminated thread when pthread_join() returns successfully.
If multiple threads wait for the same thread to terminate, all the threads wait until the target thread terminates. Then one waiting thread returns successfully. The other waiting threads fail with an error of ESRCH. After pthread_join() returns, any data storage associated with the terminated thread can be reclaimed by the application.
Return Values
pthread_join() returns zero when the call completes successfully. Any other return value indicates that an error occurred. When any of the following conditions are detected, pthread_join() fails and returns the corresponding value.
- ESRCH - No thread could be found corresponding to the given thread ID.
- EDEADLK - A deadlock would exist, such as a thread waits for itself or thread A waits for thread B and thread B waits for thread A.
- EINVAL - The thread corresponding to the given thread ID is a detached thread. pthread_join() works only for target threads that are non-detached.
Example
#include<stdio.h> #include<pthread.h> void * my_func(void * args) { printf("My thread function called\n"); } void main() { pthread_t pid; int ret; ret = pthread_create(&pid, NULL, &my_func, NULL); if(ret != 0) printf("pthread_create failed\n"); ret = pthread_join(pid,NULL); if(ret != 0) printf("pthread_join failed\n"); }
No comments:
Post a Comment