为什么会“同时为真"?使用100%的CPU资源? [英] Why will "while true" use 100% of CPU resources?

查看:51
本文介绍了为什么会“同时为真"?使用100%的CPU资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux服务器上运行了以下Java代码:

I ran the following Java code on a Linux server:

while (true) {
   int a = 1+2;
}

这导致一个CPU内核的使用率达到100%.我对此感到困惑,因为我了解到CPU通过时间分割来处理任务,这意味着CPU将在一个时隙(CPU时间范围调度程序)中完成一项任务.如果有10个时隙,则while true任务最多应使用10%的CPU使用率,因为其他90%将分配给其他任务.那为什么是100%?

It caused one CPU core to reach 100% usage. I'm confused about this, because I learnt that CPUs deal with tasks by time splitting, meaning that the CPU will do one task in one time slot (CPU time range scheduler). If there are 10 time slots, the while true task should have at most use 10% CPU usage, because the other 90% would be assigned to other tasks. So why is it 100%?

推荐答案

如果您的CPU使用率不是100%,则该进程可以使用所需的数量(最多100%),直到其他进程请求资源的使用.进程调度程序试图最大化CPU使用率,如果没有其他进程需要,则永远不要让进程饿死CPU时间.

If your CPU usage is not at 100%, then the process can use as much as it wants (up to 100%), until other processes are requesting the use of the resource. The process scheduler attempts to maximize CPU usage, and never leave a process starved of CPU time if there are no other processes that need it.

因此,您的 while 循环将使用100%的可用空闲CPU资源,并且仅在启动其他占用大量CPU的进程时才开始使用较少的资源.(如果您使用的是Linux/Unix,则可以通过启动 while 循环,然后启动另一个占用大量CPU资源的进程,并观察%CPU下降的情况,使用 top 进行观察.循环过程).

So your while loop will use 100% of available idle CPU resources, and will only begin to use less when other CPU intensive processes are started up. (if you're using Linux/Unix, you could observe this with top by starting up your while loop, then starting another CPU intensive process and watch the % CPU drop for the process with the loop).

这篇关于为什么会“同时为真"?使用100%的CPU资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆