I observed that the CPU usage of while true sleep(1) differs greatly between Windows and macOS/Linux.
Linux/macOS: The code below will cause high CPU, even showing 130%+ CPU usage in top. (My CPU has 4 cores, so the total in top is 400%.)
Windows: To my surprise, it just shows 0% CPU usage in Windows Task Manager.
So... what is the reason?
There are Java and C# versions of the code; they show similar results.
Java
/**
* Platform=openjdk 11, test in CentOS7.5/macOS11/Windows7
*/
public class Test {
public static void main(String[] args) throws Exception {
for (Integer i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
thread.start();
if(i == 100)
thread.join();
}
}
}
C#
/**
* sdk=NET5, test in CentOS7.5/macOS11/Windows7
*/
class Program
{
static void Main(string[] args)
{
var threadList = new List<Thread>(100);
foreach (var index in Enumerable.Range(1, 100))
{
var thread = new Thread(() =>
{
while (true)
{
Thread.Sleep(1);
}
});
thread.Start();
threadList.Add(thread);
}
threadList[0].Join();
}
}
2021.5.8
I've implemented goroutine version of this demo, it just used less than 5% CPU usage at CentOS7. So can I consider the CPU usage was consumed by the context switching of Linux LWP?
Go
package main
import (
"runtime"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
for i := 0; i < 100; i++ {
go sleep()
}
runtime.Gosched()
wg.Add(1)
wg.Wait()
}
func sleep() {
for {
time.Sleep(time.Millisecond)
}
}