Control and separation of linux--threads

Source: Internet
Author: User
Tags terminates

First, the concept of threading

A thread is a basic execution flow within a process that is an entity of system scheduling. Processes are exclusive and threads are shared. Each thread shares the process's file descriptor, how the signal is processed, the current working directory, the user ID (UID), and the group ID (GID). However, some resource threads are private, such as thread ID, stack space, and context (including the values of various registers). program counter and stack pointer), occupy space, signal shielding word, scheduling priority. Just like a process if it is a family, the thread is the member of this family, each family member has a public space (restaurant, living room). Of course, every family member also has its own private space.

Second, the control of the thread

Creating Threads and terminating

Created with function Pthread_create (), successfully returned 0, failed back basics error number. Call Pthread_create () after creating a new thread. The current thread is returned from Pthread_create () to continue execution down. The code executed by the new thread is determined by the function pointer start_routine. The function Start_routine function receives a parameter that is passed to it by the Arg of Pthread_create (). The return value type of type Void*,start_toutine is also void*,start_toutine returned, the thread exits, and other threads can call Pthread_join () to get the Start_toutine return value. The Start_toutine function can be terminated by ①return (void*), ②pthread_exit (void*), ③pthread_cancel (Pthread_self ()) three.

  1  #include <stdio.h>  2  #include <pthread.h>  3 void  * thread_run (Void* arg)   4 {  5     int  count=5;  6     while (1)   7     {   8         printf ("This is a thread, Thread id is\n "Pthread_self ());  9          Sleep (1); 10     } 11     //return  (void*) 1;  12     //pthread_exit ((void*) 2); 13     //  Pthread_cancel (Pthread_self ());  14 } 15 int main ()  16 { 17      pthread_t id; 18     int ret=pthread_create (&id, Null,thread_run,null); &nBsp;19     int count=10; 20     while (count-->0 )  21     { 22         printf (" This is a main thread,thread id is %u\n ", Pthread_self ()); 23          sleep (1); 24     } 25      void * ted=0; 26     pthread_cancel (ID);  27     pthread_join (id,&ted);  28     printf ("Return  success %d\n ", (int) Ted);  29 }

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M01/7F/14/wKioL1cTI5OyFxmNAANCmi8sCcI754.jpg "title=" thread. JPG "alt=" wkiol1cti5oyfxmnaancmi8scci754.jpg "/> can be seen:

1, if return through return. The value received by the Pthread_join is the return value of the thread

2. If the thread is called by another thread, the pthread_cancel exception terminates. The error code is returned

3, if the call Pthread_exit terminated. The Pthread_join store is the parameter passed to Pthread_exit.

4, two threads have a different thread number


Three, thread separation

Thread at any point in time. is either associative (joinable) or separable (detached). A thread that can be combined can be recycled by other threads and killed. Its memory resource is not freed until it is reclaimed by another thread. A separable thread cannot be recycled or killed by another, and its memory resource is automatically released by the system when it terminates. By default. Threads are created to be combined. To avoid memory leaks, each of the threads that can be combined should either be displayed for recycling, called Pthread_join, or separated by the Pthread_detach function.

  If a binding thread ends up running but is not pthread_join, its state is similar to a zombie process in progress, that is, some of the resources are not recycled, so the creator should call Pthread_join to wait for the thread to finish. And can get the thread exit code, reclaim its resources. When Pthread_join is called, the caller is blocked if the thread does not end up running. This is possible to add code Pthread_detach (Pthread_self ()) to a child thread, or the parent thread calls Pthread_detach (thread_id) non-blocking and can be returned immediately. This sets the state of the child thread to detached (detached), so that all resources are freed automatically when the thread finishes running.

  1  #include <stdio.h>  2  #include <pthread.h>  3 void*  thread_run (Void* arg)   4 {  5     pthread_detach ( Pthread_self ());  //Detach Thread   6     printf ("This is a thrad  \n ");  7     return  (void*) 1;  8 }  9  int main ()  10 { 11     pthread_t id; 12      int ret= pthread_create (&id,null,thread_run,null); 13      printf ("this is a main thread\n"); 14      Sleep (1);  15  16     int res=pthread_join (Id,NULL); 17      if (res==0)  18     { 19          printf ("pthrad wait succced\n"); 20          return 0; 21     } 22     else 23      { 24         printf ("pthread  wait faile\n "); 25         return 1; 26      } 27     return 0; 28 }

650) this.width=650; "src=" http://s4.51cto.com/wyfs02/M00/7F/17/wKiom1cTMeXjafr_AACavysWnN8526.jpg "title=" thread separation. JPG "alt=" Wkiom1ctmexjafr_aacavyswnn8526.jpg "/>

If Pthread_detach (Pthread_self ()) in the thread is commented out, the result is as follows, because the other threads can join and kill the child thread process after the detach is removed from the thread, and then release the memory resource. The above is separated from the child process, so the other threads cannot access it, and the join returns fail

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M00/7F/14/wKioL1cTMvzifinYAAClEkKL-NU838.jpg "title=" thread join . JPG "alt=" Wkiol1ctmvzifinyaaclekkl-nu838.jpg "/>


Summarize:

The thread's control is from the creation of the thread--the three termination methods of the child thread--and the other thread join thread. The return value of the join is different in the way it is terminated. Thread separation, if a child thread joins Pthread_detach () and the thread is set to a detachable thread, the thread exits and automatically frees the memory resource, without causing a memory leak. If not set, the join is used to display the receive, and then release the resource, without causing a memory leak.

Control and separation of linux--threads

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.