[Operating system] thread basics

Operating environment This paper test code:
Centos7 x86_64
Kernel 3.10.0-693.5.2.el7.x86_64
gcc version 4.8.5
the CPU: 2 core

Multithreading Concepts

A thread is running a branch processing tasks in the process, a process that includes a main thread.
Process: resource allocation, the basic unit of management (memory management, management of open files, etc.).
Thread: scheduling, the basic unit of execution.
In Linux, also known as lightweight process threadLWP.
Each time you create a new process, it is assigned a new virtual address space.
Each time you create a new thread, the thread common to the original virtual address space.

From the perspective of the Linux kernel, in fact, it is not the concept of threads. Linux all the threads as the process is implemented, threads and processes indiscriminate unity to the task_struct.

Sharing of resources between threads

  1. Virtual address space.
  2. File descriptor table.

When a thread is created, it added CLONE_VM mark, soThread memory descriptor will point directly to the memory descriptor of the parent process.

if (clone_flags & CLONE_VM) {
	// current 是父进程而 tsk 在 fork() 执行期间是共享子进程
    atomic_inc(&current->mm->mm_users);
    tsk->mm = current->mm;
}

Do not share resources between threads

  1. Stack.
  2. Context information (register information).
  3. errno (each thread has its own separate error code).

For Linux process or the main thread, its stack is generated when the fork is actually copied his father's stack address space, and then copy (cow) and dynamic growth when writing.
However, for the main thread to create a sub-thread, its stack will no longer be such, but rather fixed in advance.
Thread stack can not grow dynamically, once exhausted is gone, which is the process of generating and fork in different places.

Advantages thread

Compared to processes for:

  1. Creating and destroying a smaller cost.
  2. Scheduling switching overhead is smaller.
  3. Thread consumes less resources.

Multithreaded programs can take advantage of multicore processors.
chestnut:Because my virtual machine is a 2-core, so most use the CPU 200%
Here Insert Picture Description

Shortcoming thread

  1. Robustness of the program to reduce the abnormal termination of a thread will cause the entire process terminates abnormally.
  2. Programming && debugging more difficult (the introduction of the thread-safety issues).

Use thread

  1. CPU-intensive programs to enhance efficiency.
  2. IO intensive program to improve the experience.
    • IO conducted through the network.
    • In response UI interface.

EOF

Published 73 original articles · won praise 90 · views 40000 +

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/104976977