Self-righteous multithreading (1) and self-righteous multithreading (

Source: Internet
Author: User

Self-righteous multithreading (1) and self-righteous multithreading (

Multithreading is not applicable in many web development scenarios, and most of the scenarios that are applied to multithreading are simple. Most of them can be replaced by tasks, therefore, many web developers have a very simple understanding of multithreading, which leads to many unpredictable bugs. Therefore, they have written a lot of logic to bypass, so I want to talk about multithreading and try to build a better place to give everyone a broader vision.

This article describes the performance and thread security.

First explain why the more threads, the better:

When talking about multithreading, we must talk about cpu. A single core cpu can only execute one thread (limited by the current technology) at the same time. For hyper-threading cpu (intel patented, the cpu with hyper-threading technology allows one core to execute two threads at the same time, and two cores are displayed in the windows operating system.

Each thread must contain the following elements:

1. The thread kernel object created by the system for each thread, including context.

2. The thread environment block is a piece of memory that contains the thread's first exception handling link.

3. User Mode stack and kernel mode stack.

4. Notification of DLL thread link and thread Separation

This is what the system needs to create during thread initialization when creating a new thread.

As mentioned above, a single-core CPU can only run one thread at a time. When a CPU is running one thread, A lot of data in this thread has been stored in the high-speed cache of the CPU. During this switchover, we need to switch to another thread for execution, this thread may execute another code and need to read another data. At this time, the CPU needs to re-fetch data from the memory to fill the cache. The process in which the CPU fetches data from the memory is slow compared with that in the cache. That is to say, when we frequently switch threads, CPU requires a lot of extra work. That is to say, when only one core CPU is used, one thread must be faster than multiple threads with the same function. There is a conflict here, that is, the system cannot have only one thread. The system also involves many of its own system threads and other application threads, when the system performs thread switching (the system determines which thread to call), it will involve a thread priority problem, and this scheduling method (a relatively reasonable and intelligent algorithm) we are not controllable, so when your program has multiple threads, the probability of switching to your thread will increase during thread switching, therefore, it cannot be said that a thread must be faster than multiple threads. Here is only a rough relative theory.

In this case, we should avoid thread switching whenever possible when writing code, so that the CPU can execute this thread as much as possible. However, under what circumstances will thread switching occur easily (all of the following thread switches are relative or possible because thread scheduling is uncontrollable ).

For example, I have the following code:

public static string ReadText(string path)        {            string text = "";            if (File.Exists(path))            {                using (Stream fs = File.Open(path, FileMode.Open))                {                    using (StreamReader sr = new StreamReader(fs))                    {                        text = sr.ReadToEnd();                        sr.Close();                    }                }            }            return text;        }

This is a very common IO read. At this time, a request will be sent to the IO thread, and then wait for the IO response, the system will lock this thread (this is a great design), let the CPU do other things, wait until the execution of the response is complete, then wake up the thread. Similarly, this will happen when reading the database and some other IO requests. If there is a user request, we will execute such a piece of code, when there are more and more user requests, the system will create more and more threads (the overhead of the thread itself is very expensive), and when the IO reads the response, there will be more and more threads gradually wake up, at this time, the system will be exhausted by thread switching, and you will find that the performance starts to drop dramatically.

Similarly, when I have the following code:

lock(object){    ...}

When multiple threads execute this code, it will be very interesting.

For example, 1-10, A total of 10 threads need to execute this Code. For example, if the cpu is two threads (A and B respectively, 1 and 2 respectively ), when 1 is executed, 2 is locked. At this time, cpu B starts thread switching. If this code is long, A may not be able to finish execution in A short period of time, and it will appear, scheduling A lock, continue switching, re-scheduling, re-locking, and then switching A loop, until all threads are locked.

When the execution of 1 is completed, all the locked threads are awakened at this time, and allocated to A and B again. Then, when A is executed here, B will see a loop like "re-scheduling", "re-locking", and "re-switching. Therefore, when developing multiple threads, try to avoid sharing resources.

Related Article

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.