At any point in time, threads can be combined (joinable) or separated (detached ). A combined thread can be reclaimed and killed by other threads. Before being recycled by other threads, its memory resources (such as stacks) are not released. On the contrary, a separate thread cannot be recycled or killed by other threads, and its memory resources are automatically released by the system when it is terminated.
By default, a thread is created to work together. To avoid Memory leakage, each thread that can be combined should be either explicitly recycled, that is, calling pthread_join; or being separated by calling the pthread_detach function.
[Cpp]
Int pthread_join (pthread_t tid, void ** thread_return );
If successful, 0 is returned. If an error occurs, the value is non-zero.
Int pthread_join (pthread_t tid, void ** thread_return );
If successful, 0 is returned. If an error occurs, the value is non-zero. The thread waits for other threads to terminate by calling the pthread_join function. The pthread_join function is blocked until the thread tid is terminated. Assign the (void *) pointer returned by the thread routine to the position indicated by thread_return, and reclaim all memory resources occupied by the terminated thread. [Cpp] view plaincopyprint? Int pthread_detach (pthread_t tid );
If successful, 0 is returned. If an error occurs, the value is non-zero.
Int pthread_detach (pthread_t tid );
If successful, 0 is returned. If an error occurs, the value is non-zero.
Pthread_detach is used to separate tid threads that can be combined. Threads can separate themselves by calling pthread_detach with pthread_self () as the parameter.
If a combined thread stops running but is not joined, its status is similar to Zombie Process in the Process, that is, some resources are not recycled, therefore, the thread Creator should call pthread_join to wait for the thread to finish running, get the thread exit code, and recycle its resources.
After pthread_join is called, if the thread is not running, the caller will be blocked. In some cases, we do not want this to happen. For example, when the main thread creates a subthread for each new connection request in the Web server for processing, the main thread does not want to block it because it calls pthread_join (because it still needs to process the connection requests that come later). In this case, you can add code to the Child thread.
Pthread_detach (pthread_self ())
Or the parent thread calls
Pthread_detach (thread_id) (non-blocking, can be returned immediately)
This sets the sub-thread status to detached. As a result, all resources are automatically released after the thread finishes running.