Deeply understand the meaning of Thread. sleep, thread. sleep

Source: Internet
Author: User
Tags sleep function

Deeply understand the meaning of Thread. sleep, thread. sleep

Repost a very good article on sleep, the original http://www.cnblogs.com/ILove/archive/2008/04/07/1140419.html

We may often use the Thread. Sleep function to suspend the Thread for a period of time. Do you understand the usage of this function correctly? Consider the following two questions:

Suppose it is 12:00:00. 000. If I call Thread. Sleep (1000), this Thread will not be awakened at 12:00:01. 000?
Someone's Code uses a seemingly unknown sentence: Thread. Sleep (0 ). Since Sleep is 0 ms, what is the difference between Sleep and this code?
Let's first review the operating system principles.

There are many strategies for CPU competition in the operating system. The Unix system uses the time slice algorithm, while Windows is preemptible.

In the time slice algorithm, all processes are in a queue. The operating system allocates a period of time to each process in their order, that is, the time that the process allows to run. If the process is still running at the end of the time slice, the CPU is denied and allocated to another process. If the process is blocked or ended before the time slice ends, the CPU will be switched immediately. All you need to do in the scheduling process is to maintain a list of ready processes. When a process runs out of its time slices, it is moved to the end of the queue.

The so-called preemptible operating system means that if a process gets the CPU time, It will completely occupy the CPU unless it gives up CPU usage. Therefore, it can be seen that in the preemptive operating system, the operating system assumes that all processes are "good character" and will take the initiative to exit the CPU.

In a preemptible operating system, assuming there are several processes, the operating system will be based on their priority and hunger time (for how long it has not used the CPU ), calculate a general priority for them. The operating system will hand over the CPU to the process with the highest overall priority. After a process is executed or is manually suspended, the operating system recalculates the total priority of all processes, and then selects the highest priority to control the CPU.

We use cake-sharing scenarios to describe these two algorithms. Suppose there are a steady stream of cakes (Continuous Time), a pair of knives and forks (a CPU), and 10 people waiting to eat cakes (10 processes ).

If it is a Unix operating system responsible for dividing the cake, then he will set the rule as follows: Everyone will come up to eat for one minute, and it will take another time. When the last person finishes eating, start from scratch. Therefore, no matter whether these 10 people have different priorities, different levels of hunger, and different amounts of meals, each person can take one minute to come up. Of course, if someone is not very hungry or has a small amount of food and will be full after 30 seconds, then he can say to the operating system: I am full (suspended ). Then the operating system will let the next person come.

If the Windows operating system is responsible for dividing the cake, the scene will be very interesting. He will set the rule as follows: I will calculate a priority for each of you based on your priority and hunger level. The person with the highest priority can come up to eat the cake-until you don't want to eat it. When this person is finished, I will calculate the priority of each person based on the priority and hunger level, and then assign it to the person with the highest priority.

In this way, this scene is interesting-some may be PPMM, so it has a high priority, so she can often eat cakes. Another person may be an ugly man, but with ws, the priority is very low, so it takes him a long time (because as time passes, he will become increasingly hungry, therefore, the total priority is higher and higher, so it will be his turn one day ). In addition, if he accidentally gets a big fat man with a knife and a cross, because of his large amount of food, he may occupy the cake for a long time, causing the people next to him to swallow water there...
In addition, this may happen: the result calculated by the operating system, PPMM 5, has the highest priority and is much higher than that calculated by others. Therefore, let's eat the cake on the 5th. After eating for a while on the 5th, I felt that I was not so hungry, so I said "I don't want to eat" (suspended ). Therefore, the operating system recalculates the priority of all users. Because she had just eaten on the 5th, her hunger level became lower, so her total priority became lower. Other people waited for a while, and her hunger level became greater, so the total priority is also increased. However, at this time, it is still possible that the priority of the 5th is higher than the other, but now it is only a little higher than the other-but she still has the highest overall priority. Therefore, the operating system will say: mm 5 comes up to eat cake ...... (Mm 5 was so depressed that it was not just eaten ...... People want to lose weight ...... Who told you to be so beautiful, and gained such a high priority ).

So what is the Thread. Sleep function? We also use the cake splitting scenario we just described. In the above scenario, MM 5, after eating a cake, felt that she had got 8 full points. She thought she would not want to eat the cake any more in the next half hour, then she will talk to the operating system: Don't ask me to eat cake in the next half hour. In this way, when the operating system re-calculates the total priority of all people in the next half hour, it will ignore mm 5. The Sleep function does this. He told the Operating System "How many milliseconds will I not participate in CPU competition ".

After reading the role of Thread. Sleep, let's start with two questions.

The answer to the first question is: Not necessarily. The reason is that you only tell the operating system that in the next 1000 milliseconds, I don't want to participate in CPU competition any more. Then, after 1000 milliseconds, another thread may be using the CPU, so the operating system will not re-allocate the CPU until the thread is suspended or ended, even if it happens to be the turn of the operating system for CPU allocation, the current thread is not necessarily the one with the highest total priority, and the CPU may be preemptible by other threads.

Similarly, a Thread has a Resume function that is used to wake up a suspended Thread. As mentioned above, this function only "tells the operating system that I have been involved in CPU competition since now", and the call of this function does not immediately allow this thread to gain CPU control.

For the second question, the answer is: yes, and the difference is obvious. Suppose there is another PPMM 7 in the cake-sharing scenario just now. Her priority is also very high (because it is very beautiful ), therefore, the operating system always calls her to eat cake. Besides, I also like to eat cakes on the 7th, and the amount of meals is huge. However, she is very kind and has a good character on the 7th. If someone else needs to eat cake better than me, I will give it to her. Therefore, she can say to the operating system every few times: Let's recalculate the total priority of everyone. However, the operating system does not accept this suggestion-because the operating system does not provide this interface. So mm 7 changed the saying: "Don't ask me to come and eat cake in the next 0 ms ". This command is accepted by the operating system, so the operating system will re-calculate the total priority of everyone-note that this time is calculated together with 7, because "0 milliseconds have passed. Therefore, if no one needs to eat the cake on the 7th, the next time the 7th will be called to eat the cake.

Therefore, Thread. Sleep (0) is used to "trigger the operating system to immediately re-compete with the CPU ". The competition result may be that the current thread still obtains CPU control, and may switch to another thread to obtain CPU control. This is also a Thread that we often write in a large loop. sleep (0), because this gives other threads such as the Paint thread the power to control the CPU, so that the interface will not be suspended.

The last note, although the above mentioned "unless it gives up using the CPU itself, it will occupy the CPU completely ", but this behavior is still restricted-the operating system will monitor your CPU occupation. If you find that a thread occupies the CPU for a long time, it will force the thread to be suspended, therefore, there will not be a situation where "a thread has been occupying the CPU for a long time. As for our large loop, the program is suspended, not because the thread has been occupying the CPU. In fact, during this time, the operating system has already had many CPU competitions, but other threads immediately quit after obtaining CPU control, as a result, the thread continues to execute the loop again, so it took a long time to be forcibly suspended by the operating system... Therefore, the response to the interface looks like this thread has been occupying the CPU.

At the end of the article, the threads and processes in the article are a bit messy. In fact, at the Windows principle level, CPU competition is at the Thread level. In this article, we can regard the processes and threads here as the same thing.

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.