In general, there are two scenarios for POSIX thread termination: normal termination and abnormal termination. A thread's active invocation of pthread_exit () or return from a thread function causes the thread to exit normally, which is a predictable exit method, which is unpredictable if the thread exits with the intervention of another thread, or because of an error in its own operation (such as access to an illegal address).
Thread-terminated synchronization and its return value
In general, each thread in the process runs independently of each other, the thread terminates without notification, does not affect other threads, and the resources consumed by the terminated thread are not freed as the thread terminates. Just as there is a wait () system transfer between processes to terminate and release resources synchronously, there is a similar mechanism between threads, which is the Pthread_join () function.
| void Pthread_exit (void *retval) int pthread_join (pthread_t th, void **thread_return) int pthread_detach (pthread_t th) |
The caller of Pthread_join () suspends and waits for the th thread to terminate, retval is the return value of the pthread_exit () caller thread (thread ID of th), and if Thread_return is not NULL, *thread_return= retval It is important to note that a thread allows only one thread to use Pthread_join () to wait for its termination, and the waiting thread should be in a join state, that is, a non-detached state.
If a thread in the process executes Pthread_detach (TH), the th thread will be in the detached state, allowing the th thread to release its consumed memory resources at the end of the run and not be synchronized by Pthread_join (), Pthread_ After detach () is executed, an error is returned to the TH request Pthread_join ().
The memory consumed by a join thread is freed only after the Pthread_join () is performed on it, so in order to avoid a memory leak, all threads are either set to detached or need to be reclaimed using pthread_join ().
About Pthread_exit () and return
Theoretically, the function of Pthread_exit () and the thread-body function exits is the same, and Pthread_exit () is automatically called internally at the end of the function to clean up thread-related resources. But in fact the two are very different because of the compiler's processing.
Calling Pthread_exit () in the process main function (main ()) only leaves the thread where the main function (which can be said to be the primary thread of the process) exits, and if it is return, the compiler will make it invoke the code that the process exits (such as _exit ()). This causes the process and all its threads to finish running.
Second, the active call to return in the thread host function, if the return statement is contained in the Pthread_cleanup_push ()/pthread_cleanup_pop () pair, will not cause the cleanup function to execute, but will result in segment Fault
Thread termination mode