Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 270
Steffen Avatar asked Feb 19 '10 16:02

Steffen


1 Answers

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.

like image 130
Thomas Pornin Avatar answered Sep 26 '22 23:09

Thomas Pornin