Thread creation and wait

Source: Internet
Author: User
Tags posix terminates


I. Overview:

Let's talk about why you should have a thread. As we all know, a process can only make one execution flow, although it is possible to create child processes, but the overhead of creating, terminating, switching between processes and interprocess communication is large, so modern operating systems generally use threads.

Now let's talk about the threading capabilities I know. It is common to think that processes are responsible for allocating resources, while threads are responsible for scheduling and execution. Threads are also called lightweight processes. And the traditional process is responsible for allocating resources, but also assume the execution of a thread.

The difference between a process and a thread: In addition to the above features and performance, you can also differentiate from the perspective of process management. In a single-threaded model, the representation of a process consists of its process control block, the user address space, and the user stack that manages the call/return behavior in the process execution, and the kernel stack. In a multithreaded environment, a process has only one process control block and user address space associated with it, and threads have a separate stack, as well as separate control blocks (including registers, priorities, and other thread-related state information). such as: (Excerpt from the operating system essence and design principles of the 4th chapter)

Note: If you are on a multiprocessor machine, the performance of multithreading will be more optimal.


Two. Correlation function: (PS: The line libraries function here is defined by the POSIX standard, called POSIX thread or pthread. )

    1. Pthread_create:int pthread_create (pthread_t *pthread, const pthread_attr_t *attr,

      void * (*start_toutine) (void *), void *arg)

function function: Creates a thread that enables the thread to start executing from the function referred to in the function pointer passed in.

Pthread parameter: Output type parameter, the successful creation will put the thread ID into the inside.

attr parameter: Used to set the properties of a thread, such as the detach State property of a thread, the size of a line stacks, and so on. It is generally null to do so.

Start_toutine parameter: A function pointer that indicates where the thread starts execution.

ARG parameter: The parameter of the function passed into the function pointer.

Return value: All Pthread functions are returned with a success of 0, and a failure returns an error number. You can display the error number with strerror.

PS: The main thread will return from the function to continue execution.


2.pthread_exit:void pthread_exit (void *retval)

function function: A thread can invoke its own logoff operation.

retval parameter: The value returned when exiting.


3.pthread_cancel:int Pthread_cancel (pthread_t pthread)

function function: Unregisters a thread with a thread ID of pthread.

Return value: Successful return 0, failure returns an error number.


4.pthread_join:int Pthread_join (pthread_t pthread, void** retval)

function function: Suspends the thread ID pthread thread until the thread terminates and the terminating state is persisted to retval.

retval parameter: The output type parameter that holds the terminating state of the thread termination. Different termination methods have different termination states:

(1). If the thread returns by return, the cell in RetVal is the return value of the thread function.

(2). If a thread is called by another thread, the pthread_cancel exception terminates, and retval points to a cell that holds a constant pthread_calceled.

(3). If the thread itself calls the Pthread_exit () function to terminate, retval points to the cell that holds the arguments passed to Pthead_exit ().

Return value: Successful return 0, failure returns an error number.


Three. Related code: (PS: Compile to add-lpthread)

    1. Create a process:

1  #include <stdio.h>                                                                                                                                                        2  #include <stdlib.h>  3  #include <pthread.h>   4   5 pthread_t tid;  6   7 void* create_thread (void *ptr)    8 {  9     printf ("%s . pid is:%d  tid  is:%ul \n ", (char *) ptr,  (int) getpid (),  (Unsigned long long) pthread_self ()) ; 10     return null; 11 } 12  13 int  Main ()  14 { 15     int err = pthread_create (&tid,  NULL, create_thread,  "I ' M a thread");  16     if (err  != 0)  17     { 18          printf ("create thread failed!  info is :%s ",  strerror (err)); 19          exit (err); &NBSP;20&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;21&NBSP;&NBSP;22&NBSP;&NBsp;   printf ("main thread run. pid is:%d  tid is:%ul \n ",  (int) getpid (),  (Unsigned long long) pthread_self ());//linux  under TID is an address value  23      sleep (1);  24     return 0; 25 }

Execution Result:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7F/32/wKiom1cWMEXDM0elAAA1CwtyzGo668.png "title=" 2016-04-19 21:18:39 screen. png "alt=" Wkiom1cwmexdm0elaaa1cwtyzgo668.png "/>


2. Thread Waits:

 1  #include <stdio.h>                                                                                                                                                        2  #include <stdlib.h>  3  #include <pthread.h >  4   5 void *create_thread1 (void *ptr)   6 {  7      printf ("this is thread1\n");  8     return  (void  *) 1;  9 } 10  11 void *create_thread2 (void *ptr)  12  { 13     printf ("this is thread2\n"); 14      pthread_exit ((void *) 2);  15 } 16  17 void *create_thread3 ( VOID&NBSP;*PTR)  18 { 19     while (1)  20      { 21         printf ("this is thread3,waiting  for be calceled.....\n ");  22         sleep (1 ); 23     } 24     return null; 25  } 26  27 int main ()  28 { 29     pthread_t tid; 30      void* ret; 31  32     int err1  = pthread_create (&tid, null, create_thread1, null); 33      if (err1 != 0)  34     { 35          printf ("create thread failed!");  36     } 37     pthread_join (Tid, &ret);  38     printf ("thread is returned,tid is:%ul return  Code is:%d \n ",  (Unsigned long long) pthread_self (),  (int) ret); 39   40     int err2 = pthread_create (&tid, NULL,  Create_thread2, null);  41     if (err2 ! = 0)  42     { 43          printf ("create thread failed!");  44     } 45     pthread_join (Tid, &ret);  46     printf ("Thread is exited,tid is:%ul return code  is:%d \n ",  (Unsigned long long) pthread_self (),  (int) ret);  47  48      int err3 = pthread_create (&tid, null, create_ Thread3, null);  49     if (err3 != 0)  50      { 51         printf ("create thread  Failed! ");  52     } 53     sleep (3); 54      pthread_cancel (TID);  55     ptHread_join (Tid, &ret);  56     printf ("Thread is canceled,tid  is:%ul return code is:%d \n ",  (Unsigned long long) pthread_self (),   (int) ret);  57  58     return 0; 59 }

Execution Result:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7F/33/wKiom1cWPnLQqc_rAAA-Ol4ljcQ597.png "title=" 2016-04-19 22:16:45 screen. png "alt=" Wkiom1cwpnlqqc_raaa-ol4ljcq597.png "/>

This article is from "Narcissus" blog, please make sure to keep this source http://10704527.blog.51cto.com/10694527/1765574

Thread creation and wait

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.