A program can use multithreading to improve efficiency or to isolate various processes. Let’s say this thread handles problem A, and that thread handles problem B. A thread is an execution unit within a process that shares the resources of the process. In theory, you can open up as many threads as you have cpus, or CPU cores. Single threads do not take advantage of multiple cpus.
The biggest problem of multithreading is how to solve the problem of resource contention.
Thread sleep. Suspends the thread from competing for the CPU. In C#, threads can be suspended (hibernated) with this statement:
Thread.Sleep(60 * 1000);Copy the code
A minute later? Is it right away? No, this statement only means that the thread will wake up after 1 minute and participate in the CPU usage contention. Whether it can be snatched at once depends on its fate.
Thread priority IF a thread has a high priority, it is easy to grab the CPU. But low priority doesn’t mean getting robbed all the time. A thread that gets robbed the longer it waits, and then gets higher and higher in priority, eventually snatching the CPU and resetting it when it’s done. Philosophers versus chopsticks? The scope of the operating system.
Number of threads The number of threads is related to the hardware environment, especially the NUMBER of cpus. It’s also about the nature of the software. For example, if the thread consumes a lot of IO, then the number of threads can be set to a higher number, because the thread is busy with IO more, which consumes less CPU. If the main consumption is CPU, set the number of threads to the number of cpus, or CPU x 2.
If you have 8 cpus and only one or two threads, there will always be idle CPU, it is not a waste.
More than the number of cpus.