Article Title: Analysis and Solution of Memory leakage caused by Linux threads. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Pthread_create (& thread, NULL, & thread_function, NULL); that's it. Parameter 2 does not set Automatic detach after the thread ends, pthread_join or pthread_detach is not used to release the thread space after execution!
This problem has been illustrated in Linux man page:
When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
That is to say, if the thread is not joined after execution, the resources of the thread will not be released, resulting in Memory leakage! There are endless troubles in the instant graph.
Solution:
Code
1 // the simplest method is to call pthread_detach after the thread execution ends to release it.
2 pthread_detach (pthread_self ());
3 // or set the PTHREAD_CREATE_DETACHED Attribute before creating a thread
4 pthread_attr_t attr;
5 pthread_t thread;
6 pthread_attr_init (& attr );
7 pthread_attr_setdetachstate (& attr, PTHREAD_CREATE_DETACHED );
8 pthread_create (& thread, & attr, & thread_function, NULL );
9 pthread_attr_destroy (& attr );
The method of Row 3 is the simplest. You can add this sentence at the end of the thread function to release the resources occupied by the thread, or set the detach attribute for the method as shown in Figure 5-11, this will also release the memory after the thread return/pthread_exit.
As a matter of fact, when valgrind checks, it has already indicated that pthread_create has not been released, but it has not been noticed before. In fact, this problem can only be exposed when the memory is accumulated for a long time. It seems that the prompt of valgrind cannot be ignored.