1. Linux multithreading, basic concepts)

Source: Internet
Author: User

NOTE: For the following content, refer to [1 ~ 6] the content is organized.

I. Basic Concepts

1. The thread is the smallest unit of independent operation in the computer. A process is the unit of resource allocation.

2. Why is multithreading used?

(1) To start a new process, you must allocate it an independent address space and create a large number of data tables to maintain its code segment, stack segment, and data segment, this is an "expensive" way of multitasking. While multiple threads running in a process use the same address space for each other to share most of the data. The space required to start a thread is much less than the space required to start a process, in addition, the time required for switching between threads is much less than the time required for switching between processes. According to statistics, the overhead of a process is about 30 times the overhead of a thread.

(2) The second reason for using multithreading is the convenient communication mechanism between threads. For different processes, they have independent data space, and data transmission can only be performed through communication. This method is not only time-consuming, but also inconvenient. The thread is not the case. Because the threads in the same process share data space, the data of one thread can be directly used by other threads, which is fast and convenient. Of course, data sharing also brings about other problems. Some Variables cannot be modified by two threads at the same time, and some subprograms declare static data, which is more likely to cause catastrophic damage to multithreaded programs, these are the things you need to pay attention to when writing multi-threaded programs.

In addition, multi-threaded programs, as a multi-task and concurrent working method, certainly have the following advantages:

1) Improve application response. This is especially meaningful for graphic interface programs. When an operation takes a long time, the entire system will wait for this operation. At this time, the program will not respond to keyboard, mouse, and menu operations, but will use multithreading technology, putting time consuming in a new thread can avoid this embarrassing situation.

2) Make the multi-CPU system more effective. The operating system ensures that different threads run on different CPUs when the number of threads is not greater than the number of CPUs.

3) Improve the program structure. A long and complex process can be considered to be divided into multiple threads and become several independent or semi-independent running parts. Such a program will facilitate understanding and modification.

3. threads are not organized according to strict parent-child levels like processes. A peer thread pool (a pool of peers) is formed with a thread related to a process ). The main influence of the concept of peer-to-peer (thread) pool is that a thread can kill any of its peer-to-peer threads or wait for any of its peer-to-peer threads to terminate. Further, each peer thread can read and write the same shared data.

4. Related functions

1) create a thread

# Include <pthread. h>

Int pthread_create (pthread_t * thread, pthread_attr_t * ATTR, void * (* start_routine) (void *), void * Arg );

Pthread_t pthread_self (void );

Int pthread_equal (pthread_t thread1, pthread_t thread2 );

Int pthread_once (pthread_once_t * once_control, void (* init_routine) (void ));

Linux supports POSIX multi-threaded interfaces, called pthread. To compile a multi-threaded program in Linux, you must include the header file pthread. h and use the library libpthread. A for link.

If a thread is created in the main thread, the program will generate a branch at the place where the thread is created, which is executed in two parts. The thread is created using the pthread_create function. 0 is returned.

Parameters:

Thread: the parameter is a pointer. When a thread is successfully created, the ID of the thread to be created is returned.

ATTR: Specifies the attributes of a thread.

Start_routine: this parameter is a function pointer pointing to the function to be called after the thread is created.

Arg: The parameter passed to the thread function.

2) thread termination

Terminate a thread in two ways.

First, return from the thread function through return,

The second method is to call the pthread_exit () function to exit the thread.

Note: First, if the main thread returns from the main function or calls the exit function to exit the main thread, the whole process is terminated and all other threads are terminated. The other is that if the main thread calls the pthread_exit function, the process will not end, and other threads will not end. The process will end when all threads are finished.

3) thread attributes

/* Man pthread_attr_init */

Typedef struct

{

Int detachstate; // whether to detach data from other threads

Int schedpolicy; // scheduling policy of the new thread

Struct sched_param schedparam; // The Running priority.

Int inheritsched; // whether to inherit the value of the caller's thread

Int scope; // The range of threads competing for CPU (priority range)

Size_t guardsize; // alert stack size

Int stackaddr_set; // stack address set

Void * stackaddr; // stack address

Size_t stacksize; // stack size

} Pthread_attr_t;

Attribute values cannot be set directly. Related functions must be used for operations. The initialized function is pthread_attr_init, which must be called before the pthread_create function.

(1) thread binding

Thread binding involves another concept: lwp: Light Weight process ). A lightweight process can be understood as a kernel thread, which is located between the user layer and the system layer. The system allocates thread resources and controls threads through lightweight processes. A lightweight process can control one or more threads. By default, the number of light processes started and the light processes to control which threads are controlled by the system are called unbound. Under the binding condition, a thread is bound to a light process. The bound thread has a high response speed because the CPU time slice is scheduled to light processes. The bound thread can ensure that there is always a light process available when needed. By setting the priority and scheduling level of the bound process, the bound thread can meet requirements such as real-time response.

The function used to set the thread binding status is pthread_attr_setscope. It has two parameters: the first is the pointer to the attribute structure, and the second is the binding type. It has two values: pthread_scope_system (bound) and pthread_scope_process (unbound ). The following code creates a bound thread.

# Include <pthread. h>

Pthread_attr_t ATTR;

Pthread_t tid;

 

/* Initialize the property value, which is set to the default value */

Pthread_attr_init (& ATTR );

Pthread_attr_setscope (& ATTR, pthread_scope_system );

Pthread_create (& tid, & ATTR, (void *) my_function, null );

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.