I was wondering if anyone could possibly help me on this subject:
Part of an .exe file in command prompt is to wait (e.g.Sleep(1500);) before showing some text for example. So how does the computer hardware delay a command for a specific amount of time.
There are a few ways a computer can do this, none of them are perfect.
- One way is for the program to throw a number of NOP instructions at the processor. Older programs used to do this to cause delays, the problem is that NOP is an actual instruction so the processor couldn't do anything else while the program was "waiting".
- Another way I've seen is for the program to issue an instruction that grabs a timestamp of sorts and saves it, then it enters a loop where it defers it's execution on the scheduler to other processes while periodically grabbing a new timestamp and comparing it to the old one. Once the difference between the saved timestamp and the new one reaches a certain amount or greater, the program exits the loop and continues operating. The problem with this method is what is called "resolution" which basically means the ability of the instruction to "wake the process up" at the end of the time period.
There are probably more but these are the ones I know about. I tend to avoid functions like Sleep() in favor of more accurate ones like WaitForSingleObject() on Win32.
One of the functions of the OS kernel is to allocate CPU time for processes (actually threads). One way to do this is to divide time into small timeslices of a constant length and assign these to threads.
Additionally, one of the kernel's amazing abilities is to start and stop threads running on a processor as it sees fit. Using this, the kernel can have a thread running on a processor for one or more consecutive timeslices, and then stop it and give the processor to a different thread.
Now, when a thread calls Sleep() (or a similar function in a UNIX system), what happens is that the kernel immediately stops the thread in the middle of its timeslice, it removes it from the list of threads that will be allocated timeslices in the future and adds it to a list of sleeping threads. Every once in a while, the kernel checks this list and those threads that are done sleeping (because enough time has passed) are added back to the other list.
The problem with this is that a call to Sleep(n) is only guaranteed to make the caller sleep for at least n milliseconds. In practice, this means that for very small values of n, Sleep() doesn't behave well. Don't use Sleep() in any situation where you need careful timing, like interactive programs (video players, games, etc.).