Fact 1: CPU time is not allocated, kernel periodic kick the busy-looping process which refuses to release CPU
There is a hardware which generate interrupt at constant interval, the interrupt is called timer interrupt or tick
. Only when tick arrives, kernel have chance to check if current running process is taking too muck cpu resource. If no interrupt triggers, the process will take control of cpu FOREVER, there won't be any chance that any other code can be run.
Fact 2: Well designed program always release CPU when nothing to do.
There are several functions or syscalls which can release CPU resource. eg. select
, epoll_wait
, blocking read/write, wait_pid
and my least favorite sleep
(I coded millions of lines, sleep
is never used except in test cases).
Calling these function will release CPU resource, then kernel can schedule CPU to other processes.
Fact 3: When all process has nothing to do and released CPU, kernel will put CPU in low power mode, which consume low power and generate less heat.
In X86 arch, kernel will use halt
instruction to put CPU into low power mode, which will actually hand the CPU, if no interrupt arrives, CPU will hang forever. (In tickless mode, tick will be disabled if no process active and CPU will hang forever if no network, hard disk, keyboard/mouse input or whatever interrupt arrives, which saves battery)
Fact 4: A single busy-looping process will raise a single CPU core usage to 100%
Fact 5: Simple busy-looping process doesn't cause CPU generate a lot heat
A simple looping with no I/O, few memory access (very low cache miss), very little branch, isn't bad. You can try one for (;;) {}
loop per core, finding that your CPU fans are still resting. Because it only uses very few gates in the chip.
Games usually run at 60fps and a frame is 1s/60 = 16ms. Typical CPU period is 10-50ms, If the game releases CPU, it isn't guaranteed it will regain CPU in the next 16ms. So games usually run a simple loop which check high-precision clock constantly to achieve frame-rate more accurately. That's why games always take 100% CPU, no matter how powerful your box is.
Fact 6: In modern system, several busy-looping process won't hang, freeze, slow your system
The scheduler will increase the priority of well designed processes which active release CPU resource and decrease the priority of busy-looping process. In modern system, it will take less than 1% cpu resource to response your keyboard/mouse input or ssh/bash, so the process which handle user input can easily beats busy-looping processes and take control of CPU resource.
Hope these will help you understand how scheduler works