When you sleep a thread, what is actually going on?
I see that sleeping a thread "pauses the current thread for a given period of time". But just how does it work?
- the sleep duration will be subject to some system-specific granularity
- sleep is blocking
- the thread leaves the CPU and stops its execution
- the thread is not consuming CPU time while sleeping
I just can't quite understand the internal and fundamental mechanics of what this all means.
I understand that there is something called the scheduler that is responsible for switching between threads.
Sources seem to indicate that this varies by OS (or hardware?) and most threads are given 1ms - 60ms or so to perform some actions before the CPU switches to another thread.
But when a thread sleeps (for example, many seconds), how does it resume? I'm guessing a timer is involved somehow, is it the motherboard's clock? Is it related to the CPU clock rate?
And even if a timer is involved, how does the CPU know when it's time to pay attention to the thread again? Wouldn't it have to constantly check in on the thread to see if it's ready? Isn't that effectively polling and therefore kind of is consuming CPU time?
Is sleeping a thread language-specific or is the OS responsible for it or is it a CPU-specific thing?
Would someone please explain this to me with basic explanations of things like the scheduler and what the CPU is doing during all of this?