Linux Thread (ii) memory release

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.