Multithreading (1) Understanding multithreading

Source: Internet
Author: User
Tags terminates

Multithreading in the project development process is very important, this series to summarize in detail, first of all to understand multithreading.

Why Windows wants to support multithreading

In the early days of the computer, the operating system had no thread concept , and the entire system ran only one thread of execution, which contained operating system code and application code. The problem with only one thread of execution is that long-running tasks prevent the execution of other tasks. For example, in the age of 16-bit Windows, applications that print documents can easily "freeze" the entire machine.

when Microsoft designed this version of the OS kernel for Windows NT, it decided to run each instance of the application in one process. a process is actually a collection of resources to be used by an instance of an application. Each process is given a virtual address space to ensure that the code and data used in one process cannot be accessed by another process. This ensures the robustness of the application instance. At the same time, the process cannot access the kernel code and data of the OS, so the application code cannot destroy the code and data of the operating system.

What happens if the application has a dead loop? If the machine has only one CPU, it executes a dead loop and cannot execute any other program. Microsoft's solution is threading. as a Windows concept, the thread's responsibility is to virtualize the CPU. Windows provides the process-specific thread (functionally equivalent to a CPU) for each process. The code of the application dies, and the processes associated with the code "freeze", but other processes (which have their own threads) do not freeze, and they continue to execute.
Threads are powerful because they allow Windows to respond at any time, even when performing long-running tasks.

So the history of multithreading can simply be summed up as: no thread (only one thread of execution)---> Ingest process---> Introduce multithreading

The cost of the thread

Threads are good for us as well as performance losses, both spatially and in time.

1, on the space

Creating a thread requires the following resources to be loaded:

    • Thread kernel objects (Threads kernel object), which are assigned and initialized by the operating system for each thread created in the system, are used primarily to describe the properties and thread context of a thread, which is a block of memory that contains a collection of registers for the CPU. For x86,x64 and IA64 CPUs, the 700,1240 and 2500 bytes of memory are used respectively.
    • Thread environment block (thread environment block, abbreviated as TEB), Teb is a block of memory allocated and initialized in user mode (the memory address that the application can quickly access), TEB consumes 1 memory pages (X86 and X64 CPUs are 4kb,ia64 CPU is 8KB).
    • User mode stack (user-mode stack), the user mode stack is used to store local variables and arguments passed to the method, and it also contains an address that indicates where the thread should proceed from when the current method returns, by default, Windows allocates 1MB of memory for each thread's user-mode stack.
    • Kernel-mode stack (Kernel-mode stack), when application code passes an argument to a kernel-mode function in the operating system, it uses the kernel-mode stack. For security reasons, Windowd copies these arguments from the thread's user-mode stack to the thread's kernel-mode stack. 32windows kernel-mode stack size 12kb,64 bit is 24KB.
    • DLL thread connection (attach) and thread detach (detach) notifications, one policy of Windows is that any time a thread is created in the process, the DllMain method of all unmanaged DLLs loaded in the process is called and passed to the method Dll_thread_ Attach logo. Similarly, any time a thread terminates, the DllMain method of all unmanaged DLLs in the process is called, and the Dll_thread_detach flag is passed to the method.

2, ON time

Because Windows wants to share the physical CPU between all the threads (logical CPUs) in the system. At any given moment, Windows assigns only one thread to a CPU, and that thread can run a "time slice" of length. When the time slice expires, Windows switches the context to another thread.

Each time slice of the switch, Windows takes about 30ms of time.

Why to use multithreading

1, the responsiveness, or the user experience, generally for the WinForm program, you can take some time-consuming tasks to another thread to handle, so that the GUI thread can respond sensitively to the user's input and operation. Otherwise, the interface will compare cards.

2, improve performance, because each CPU in Windows schedules a thread, multiple CPUs can schedule threads in parallel, so multiple tasks can be performed simultaneously to improve performance.

process, thread, and application domain relationships

Before learning more about multithreading, it is necessary to understand these three concepts and the relationships among them.

1, noun explanation

Process

or process, can be simply understood as an instance of an. exe. a process is a basic concept in a Windows system that contains a resource that is required to run a program. Processes are relatively independent, and one process cannot access the data of another process (unless distributed computing is used), and the failure of one process to run does not affect the operation of other processes, and Windows systems use processes to divide the work into separate areas. A process can be understood as a basic boundary of a program.

Thread

or thread, can be simply understood as a virtual CPU. a thread is the basic unit of execution of a process, and the first thread that executes at the process gate is considered the thread of the process. In. NET applications, the main () method is used as the portal, and when this method is called, the system automatically creates a main thread. Threads are primarily composed of CPU registers, call stacks, and thread local memory (thread locally storage,tls). The CPU registers primarily record the state of the currently executing thread, and the call stack is primarily used to maintain the memory and data that the thread invokes, and TLS is primarily used to hold the thread's state information.

application domain

or AppDomain, can be simply understood as a logical container for a set of assemblies. the CLR creates the first AppDomain (the default AppDomain) at initialization time, and the AppDomain is destroyed when the process terminates. NET is the assembly that runs in the application domain. A process can contain multiple application domains, and an application domain can contain multiple assemblies.

2, process, thread, and application domain relationships

Can be summed up with the following two pictures and two sentences.

1), a process can contain multiple threads and application domains.

2), a thread can travel through multiple application domains, but at some point the thread will only be in one application domain.

The difference between a foreground thread and a background thread

1, the difference between a foreground thread and a background thread is that the application must run out of all foreground threads to exit, and for a background thread, you can exit without considering whether it is finished and not throw an exception, and all background threads end automatically when the application exits.

2, by default, the main thread and threads created using thread are foreground threads (threads created using the thread pool and task default are background threads) unless set isbackground= true manually.

The difference between multithreading and asynchrony

Multithreading and Asynchrony are considered to be the same thing in many cases, in order for the main thread to continue executing without waiting.

But judging from the dialectical relationship, there is a difference between the two, can be summed up in a sentence.

Async is the purpose, and multithreading is one of the ways to implement asynchrony (for example, by creating another process to implement Asynchrony).

Multithreading (1) Understanding multithreading

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.