Hardware Reference
In-Depth Information
pthread_join(3)
In the earlier pthread_create() example, the main program creates my_thread() and
starts it executing. At some point, the main program is going to finish and want to exit
(or return). If the main program exits before my_thread() completes, the entire process
and the threads in it are destroyed, even if they have not completed.
To cause the main program to wait until the thread completes, the function pthread_
join(3) is used:
int pthread_join(pthread_t thread, void **retval);
thread : Thread ID of the thread to be joined with.
retval : Pointer to the void * variable to receive the returned
value. If you are uninterested in a return value, this argument
can be supplied with zero (or NULL ).
returns : The function returns zero when successful; otherwise,
an error number is returned (not in errno ).
The following example has added pthread_join(3) , so that the main program does
not exit until my_thread() exits.
int
main(int argc,char
argv) {
pthread_t tid; // Thread ID
void
∗∗
retval = 0; // Returned value pointer
int rc;
rc = pthread_create(&tid,0,my_thread,0);
assert(!rc);
rc = pthread_join(tid,&retval); // Wait for my_thread()
assert(!rc);
return 0;
}
pthread_detach(3)
The function pthread_join(3) causes the caller to wait until the indicated thread returns.
Sometimes, however, a thread is created and never checked again. When that thread
exits, some of its resources are retained to allow for a join operation on it. If there is never
going to be a join, it is better for that thread to be forgotten when it exits and have its
resources immediately released.
The pthread_detach(3) function is used to indicate that no join will be performed
on the named thread. This way, the named thread becomes configured to release itself
automatically, when it exits.
int pthread_detach(pthread_t thread);
 
Search WWH ::




Custom Search