3 ms·
Stupid question but, why doesn’t the do while tight loop result in 100% cpu usage? I often wonder how modern run loops work. They don’t burn cycles?
by john_alan 6y ago
Stupid question but, why doesn’t the do while tight loop result in 100% cpu usage?
I often wonder how modern run loops work. They don’t burn cycles?
- usrnm 6y agoIt spends most of the time waiting for IO.
- llarsson 6y agoIf you would start it and run for ten minutes and not interact with it, you would have the program just sitting there, very efficiently doing nothing, waiting in getchar().
- deleted 6y ago[deleted]
- st_goliath 6y ago> why doesn’t the do while tight loop result in 100% cpu usage? The main loop tries to read characters using the getchar() function, which in turn pokes them out of a buffer inside the "stdin" FILE struct. If the buffer is empty, somewhere inside the libc, it calls the read() system call on the standard input file descriptor to get more. If the kernel doesn't have any more data to return, the system call blocks. I.e. the kernel marks the thread as waiting for I/O and no longer schedules it. Once the kernel has data, the thread is scheduled again and the read() system call returns. And before the obvious follow up question comes: If all programs are blocking on I/O and the kernel doesn't have any threads to schedule, it schedules an "idle thread" that spends its time slice throttling down the CPU. The CPU usage that process monitor programs are displaying is basically the amount of time a CPU core is running something that isn't the idle thread.
- lloeki 6y ago> it schedules an "idle thread" that spends its time slice throttling down the CPU Specifically (AFAIK, at least back then) on x86 the kernel schedules an interrupt and sends a single HLT[0] instruction, and only wakes up when the interrupt triggers. A smartly set up interrupt would have the CPU wake up only as needed for what is required to unblock the pending blocked operations. Smarter schedulers would go as far as coalescing active events together to rush to idle yet wake up less often, and spend as much time down as possible in increasingly deeper C-states[1]. Back in the day some kernels would loop over NOP[1] instructions, so the CPU would effectively never sleep! [0]: https://en.wikipedia.org/wiki/HLT_(x86_instruction) https://en.wikipedia.org/wiki/HLT_(x86_instruction) [1]: https://gist.github.com/wmealing/2dd2b543c4d3cff6cab7 https://gist.github.com/wmealing/2dd2b543c4d3cff6cab7 [2]: https://en.wikipedia.org/wiki/NOP_(code) https://en.wikipedia.org/wiki/NOP_(code)