What exactly happens when sleeping a thread
I was wondering how the task scheduler in the operating system handles sleeping threads.
By this I mean whether a 开发者_开发知识库sleeping thread is still checked by the scheduler, or just skipped entirely when figuring out which thread to active for the next 10 ms or however long it's given.
My reason for asking this, is to figure out whether a sleeping thread consumes CPU cycles (albeit very few).
So does anyone know what happens ?
And do you know whether it's different from Windows to Linux ?
A thread runs when the CPU is executing instructions for that thread. The scheduler hands the CPU to runnable threads. A sleeping thread is just an entry into the scheduler internal tables; that thread consumes no CPU per itself, since the scheduler knows that the thread is not runnable, and thus does not give him the CPU. The entry conceptually contains the time at which the thread shall be awakened.
A sleeping thread may have an indirect cost, in management time by the scheduler itself. This really depends on the structures and algorithms employed by the scheduler; the Linux kernel scheduler is rumored to be very good at managing thousands of sleeping threads without taking too much time to decide which thread to run. Some other operating systems do not fare as well, but as a rule of thumb this effect is negligible when the total number of threads/processes is less than a thousand.
It depends on the OS implementation, but usually there is a "schedulable thread" data structure to keep things more efficient.
But some housekeeping task probably has to look at the list of all existing threads occasionally, even if not at every scheduling cycle.
精彩评论