Linux Multithreading Summary

Source: Internet
Author: User
Tags terminates

First, the understanding of the thread

1, the thread is actually a process of a flow of execution.

2, the thread is the basic unit of operating system dispatch, the process is the basic unit of allocating system resources.

3, Linux, a process is an exclusive resource of the thread, that is, in this address space only one execution flow, the process under Linux is a lightweight process (the process can be understood as a thread, can be understood as a thread under Linux), processes and threads are called PCB.

4. Each thread in a process also shares the following process resources and environment:

1) File Descriptor descriptor

2) processing mode for each signal (sig_ign, SIG_DFL or defined signal processing function)

3) Current working directory

4) User ID and group ID

5. Each thread in a process has one copy:

1) Thread ID

2) context, including values for various registers, program counters, and stack pointers

3) Stack Space

4) errno variable

5) Signal Shielding Word
6.) Scheduling priority

The Linux thread function is located in the Libpthread shared library, so the-lpthread option is added at compile time.

Second, the Line program control system

1. Creating Threads

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M02/A7/5B/wKioL1nlox3Cq64TAABZzjru9To871.png "title=" Thread.png "alt=" Wkiol1nlox3cq64taabzzjru9to871.png "/>

Return value: Successful return 0, Failure returns error number. Previously learned system functions are successful return 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, although each thread also has a errno, but this is to be compatible with other function interfaces, The Pthread library itself does not use it and returns the error code with a clearer return value.

After calling Pthread_create () in a thread to create a new thread, the current thread returns from Pthread_create () to continue execution, and the code executed by the new thread is passed to the Pthread_create function pointer Start_ Routine decided. The Start_routine function receives a parameter that is passed to it by the ARG parameter of the pthread_create, the type of which is void *, which is interpreted by what type of pointer is defined by the caller itself. The return value type of start_routine is also void *, and the meaning of this pointer is also defined by the caller itself. When Start_routine returns, the thread exits, and other threads can call Pthread_join to get the return value of the function Start_routine, similar to the parent process calling wait (2) to get the child process's exit state.

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. Call Getpid (2) to get the ID of the current process, which is a positive integer value. The type of thread ID is thread_t, which is only guaranteed to be unique in the current process, thread_t this type has different implementations in different systems, it could be an integer value, or it could be a struct or an address, so you can't simply print with printf as an integer, Call Pthread_self (3) to get the ID of the current thread.

#include <stdio.h> #include <stdlib.h> #include <pthread.h>pthread_t tid;void* thread_run (void *val) {printf ("%s:pid is:%d,tid is:%u\n", (char*) Val, (int) getpid (), (unsigned long Long) pthread_self ()); return NULL;} int main () {int err = Pthread_create (&tid,null,thread_run, "Other thread Run"), if (err! = 0) {printf ("Create Thread Erro R!info is:%s\n ", strerror (Err));} printf ("Main thread run:pid is:%d,tid is:%u\n", (int) getpid (), (unsigned long Long) pthread_self ()), sleep (1); return 0;}


Operation Result:

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/A7/5C/wKioL1nlrAvhE9EeAABfoW_MVEo589.png "title=" haha. png "alt=" Wkiol1nlravhe9eeaabfow_mveo589.png "/>

On Linux, the thread_t type is an address value, and multiple threads that belong to the same process call Getpid (2) to get the same process number, while calling Pthread_self (3) Gets the same number of threads.
Since the Pthread_create error code is not errno, so it is not possible to print the error message directly with Perror (3), you can first use Strerror (3) to convert the error code to an error message before printing.
If any thread calls exit or _exit, all threads of the entire process are terminated, and since return from the main function is equivalent to calling exit, in order to prevent the newly created thread from terminating without execution, we delay 1 seconds before the main function return. This is a stopgap measure, even if the main thread waits 1 seconds, the kernel does not necessarily dispatch the newly created thread execution.

2. Terminating threads

If you need to terminate only one thread without terminating the entire process, there are three ways to do this:
1) return from the thread function. This method does not apply to the main thread, and return from the main function is equivalent to calling.

2) One thread can call Pthread_cancel to terminate another thread in the same process.
3) The thread can call Pthread_exit to terminate itself.

It is important to note that the Pthread_exit or return pointer points to a memory cell that must be global or allocated with malloc and cannot be allocated on the stack of the thread function, because the function has exited when other threads get the return pointer.

3. Thread wait

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/A7/60/wKioL1nlwOiA5nT6AABIdAGFGQ4567.png "title=" hehe. png "alt=" Wkiol1nlwoia5nt6aabidagfgq4567.png "/>

      return value: Successful return 0, failure return error number
  the thread that called the function suspends the wait until the thread with the ID thread terminates. Thread threads are terminated in different ways, and the terminating state obtained through Pthread_join is different, summarized as follows:
1) if the thread thread returns through return, Value_ The unit that PTR points to is the return value of the thread's function.
2) if the thread thread is called by another thread, the pthread_cancel exception ends, and the cell that the value_ptr points to holds the constant pthread_canceled.
3) if thread thread is terminated by its own call to 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.

#include <stdio.h> #include <stdlib.h> #include <pthread.h>void *thread1 (void *val)  {printf ("thread 1 returning...\n");return  (void*) 1;} Void *thread2 (void *val) {printf ("thread 2 exiting...\n");p Thread_exit ((void*) 2);} Void *thread3 (Void *val) {while (1) {printf ("Pthread 3 is running,wait for be  cancal...\n "); sleep (1);} Return null;} Int main () {pthread_t tid;void *tret;pthread_create (&tid,null,thread1,null);p Thread_join (tid , &tret);p rintf ("thread1 return,thread1 id is:%u,return code is:%d\n", unsigned  long) tid, (int) tret);p thread_create (&tid,null,thread2,null);p thread_join (Tid,&tret);p rintf (" Thread2 exit,thread2 id is:%u,exit code is:%d\n ", (Unsigned long) tid, (int) tret);     pthread_create (&tid,null,thread3,null); sleep (4);p thread_cancel (tid);p Thread_join ( Tid,&tret);p rintf ("Thread3 return,thread3 id is:%u,cancal code is:%d\n ", (Unsigned long) tid, (int) Tret); return 0;}


650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M02/A7/60/wKioL1nlwf3xqs-lAADE6CA6Hcc794.png "title=" haha. png "alt=" Wkiol1nlwf3xqs-laade6ca6hcc794.png "/>

The value of the constant pthread_canceled in the Linux pthread Library is 1. You can find its definition in the header file pthread.h.

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 set the thread to the detach state, which means that you cannot call two pthread_join on the same thread. Or, if you have already called Pthread_detach on a thread, you can no longer call pthread_join.

4. Thread separation

At any point in time, the thread is either associative (joinable) or detached (detached). A binding thread can be recalled by other threads and killed by its resources. Its memory resource (such as a stack) is not freed until it is reclaimed by another thread. Instead, a disconnected thread cannot be recycled or killed by other threads, and its memory resources are automatically freed by the system when it terminates.

By default, threads are created to be combined. In order to avoid memory leaks, each of the bonded threads should either be shown to be recycled, called pthread_join, or separated by calling the Pthread_detach function. If a binding thread ends up running but not being join, its state is similar to the 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 run and get the thread's exit code. Reclaim its resources.
Since the call to Pthread_join, if the thread does not end up running, the caller will be blocked, in some cases we do not want this. For example, in a Web server, when the main thread creates a child thread for each new connection request, the main thread does not want to block because of the call to Pthread_join (because the incoming connection request continues to be processed), and the code can be added to the child thread:
Pthread_detach (Pthread_self ())
or the parent thread calls
Pthread_detach (thread_id) (non-blocking, can be returned immediately)
This sets the state of the child thread to detached (detached), so that all sources are freed automatically when the thread finishes running.

#include <stdio.h> #include <stdlib.h> #include <pthread.h>void *thread (void *val) {Pthread_detach ( Pthread_self ());p rintf ("%s\n", (char *) val); return NULL;} int main () {pthread_t Tid;int Tret = pthread_create (&tid,null,thread, "thread run ..."), if (Tret! = 0) {printf ("Create E Rror!,info:%s\n ", Strerror (Tret)); return Tret;} int ret = 0;sleep (1), if (0 = = Pthread_join (tid,null)) {printf ("Pthread wait success!\n"); ret = 0;} else{printf ("Pthread wait failed!\n"); ret = 1;} return ret;}

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/08/B2/wKiom1nlz72C1W9TAABGYidXUHI519.png "title=" haha. png "alt=" Wkiom1nlz72c1w9taabgyidxuhi519.png "/>

Linux Multithreading Summary

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.