Linux threads have two modes joinable and unjoinable. Joinable Thread: The system saves thread resources (stack, ID, exit status, and so on) until the thread exits and is join by another thread. Unjoinable Thread: The system automatically reclaims thread resources when threads exit. The Linux thread is created by default to joinable mode, so the thread exits without releasing the resource. If a large number of creation threads in the program are not processed, a memory leak will result, resulting in the inability to continue creating threads. application Example: 1. In general, we do not focus on the state of the thread, just let it perform some action, so we want to Cheng the line to unjoinable. There are three ways of actually programming, as follows:
1 //Case 1: Set to detach when creating the thread, i.e. unjoinable2 pthread_t tid;3 pthread_attr_t attr;4Pthread_attr_init (&attr);5Pthread_attr_setdetachstate (&attr,pthread_create_detached); 6Pthread_create (&tid, &attr, (void*) &thread_function, NULL); 7 8 //Case 2: Calling Pthread_detach in thread9 voidThread_function (void*p)Ten { One Pthread_detach (Pthread_self ()); A } - - //Case 3: Call Pthread_detach After the thread is created thePthread_create (&tid, NULL, (void*) &thread_function, NULL); -Pthread_detach (TID);
2. When you need to focus on the thread state, you need to call Pthread_join.
1 pthread_create (&tid, NULL, (void *) &2 pthread_join (thread_id, NULL);
Linux Thread (ii) memory release