thread creation, termination, waiting

Source: Internet
Author: User
Tags terminates

Thread Concept:


Multiple threads of the same process share the same address space, so the text Segment, Data Segment are shared, and if you define a function that can be called in each thread, if you define a global variable that can be accessed in each thread, in addition, Each thread also shares the following process resources and environment:

1. File Descriptor Descriptor

2. How each signal is processed (sig_ign, SIG_DFL, or custom signal processing functions)

3. Current working directory

4. User ID and Group ID


But some of the resources are each thread has one copy:

1. Thread ID

2. Context, including values for various registers, program counters, and stack pointers

3. Stack space

4. errno variables

5. Signal Shielding Word

6. Scheduling priority

Attention:

The-lpthread option is added at compile time.


A. Creating A thread

int Pthread_create (pthread_t *thread, const pthread_attr_t *attr,

void * (*start_routine) (void *), void *arg);


Return value: Successful return 0, Failure returns error number.


Previously learned system functions are successfully returned 0, failed to return 1, and the error number is stored in the global variable errno, and the Pthread library function is returned by the return value of the error number, because the Pthread_create error code is not saved in errno, Therefore, the error message cannot be printed directly with Perror (3), and the error code can be converted to an error message before printing with strerror (3).


After Pthread_create successfully returns, the ID of the newly created thread is filled in to the memory unit pointed to by the thread parameter. We know that the type of process ID is pid_t, the ID of each process is unique across the system, and calling Getpid (2) can get the ID of the current process and is a positive integer value. The type of thread ID is thread_t, which is guaranteed to be unique only in the current process.


B. Terminating a thread


Attention:

1. Call exit or _exit in any of the thread functions, and all threads of the entire process are terminated.

2, return from the main function, equivalent to call exit, terminate the process.


To terminate a process:

1. Return from the thread function.

2. One thread can call Pthread_cancel to terminate another thread in the same process.

3. Threads can call Pthread_exit to terminate themselves.


void Pthread_exit (void *retval);

int Pthread_cancel (pthread_t thread);

The memory cell that the Pthread_exit or return pointer points to must be global or allocated with malloc and cannot be allocated on the stack of the thread function, because the function has exited when the other thread gets the return pointer.


C. Thread waits

int Pthread_join (pthread_t thread, void **retval);

Return value: Successful return 0, failure return error number


The thread that called the function suspends the wait until a thread with the ID of thread terminates. Thread threads terminate in different ways, and the terminating state obtained through Pthread_join is different, summarized as follows:


    1. If the thread thread returns by return, Value_ptr points to a cell that contains the return value of the thread's function.


2. If the thread thread is called by another thread, the pthread_cancel exception ends, and value_ptr points to the cell where the constant pthread_canceled is stored. The value of pthread_canceled is-1


3. If thread threads are terminated by their own invocation of pthread_exit, the cell to which value_ptr points is stored is a parameter passed to Pthread_exit. If you are not interested in the terminating state of thread threads, you can pass NULL to the VALUE_PTR parameter.



In general, after a thread terminates, its terminating state is retained until the other thread calls Pthread_join to get its state. But the thread can also be set to the detach state, so that once the thread terminates, it reclaims all the resources it occupies without leaving the terminating state. You cannot call Pthread_join on a thread that is already in the detach state, and such a call will return EINVAL. Calling Pthread_join or Pthread_detach on a thread that has not yet been detach can place the thread in the detach state, that is, you cannot call two pthread_join on the same thread, or if you have already called a thread Pthread_detach, you can no longer call pthread_join.


int Pthread_detach (pthread_t thread);


Return value: Successful return 0, Failure returns error number.

  1  #include <stdio.h>  2  #include <pthread.h>  3 void* &NBSP;PTHREAD_RUN1 (Void* arg)   4 {  5     printf ("This  is a thread1,pid:%d,tid:%ld\n ", Getpid (), pthread_self ());  6      return  (void*) 1;  7 }  8   9 void* pthread_run2 ( Void* arg)  10 { 11     printf ("This is a thread2, Pid:%d,tid:%ld\n ", Getpid (), pthread_self ());  12     pthread_exit ((void*) 2);  13 } 14  15 void* pthread_run3 (Void* arg)  16 { 17      while (1)  18     { 19       printf ("this is a thread3,pid:%d,tid:%ld\n", Getpid (), pthread_self ()); 20      &nBsp;sleep (1); 21     } 22      return  Null; 23 } 24 int main ()  25 { 26     pthread_ t tid; 27     void* ret; 28  29      pthread_create (&tid,null,pthread_run1,null);  30     pthread_join (Tid, &ret);  31     printf ("thread1,tid:%ld,return code:%d\n", Tid, (int) ret);  32  33     pthread_create (&tid,null,pthread_run2,null);  34      pthread_join (Tid,&ret);  35     printf ("Thread2 , tid:%ld,return code:%d\n ", Tid, (int) ret);  36  37     pthread_ Create (&tid,null,pthread_run3,null);  38     sleep (5); 39      pthreAd_cancel (TID);  40     pthread_join (Tid,&ret); 41      printf ("thread3,tid:%ld,return code:%d\n", Tid, (int) ret); 42      return 0; 43 } result: [[Email protected] thread]$ vim thread.c[[email  protected] thread]$ ./threadthis is a thread1,pid:2749,tid:-1216423056thread1, tid:-1216423056,return code:1this is a thread2,pid:2749,tid:-1216423056thread2,tid:- 1216423056,return code:2this is a thread3,pid:2749,tid:-1216423056this is a  thread3,pid:2749,tid:-1216423056this is a thread3,pid:2749,tid:-1216423056this is  a thread3,pid:2749,tid:-1216423056this is a thread3,pid:2749,tid:-1216423056thread3, Tid:-1216423056,return code:-1




thread creation, termination, waiting

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.