linux下某个进程的CPU利用率一直在100%以上,明显不正常
top查看进程使用情况,发现某进程的CPU使用率在100%以上
定位具体线程CPU使用情况
top -H显示所有线程的CPU使用率
找到CPU使用率高的线程
分析具体代码解决问题。
一般线程CPU使用率过高的问题就是有while死循环一直在跑,但是没有对线程进行sleep或者usleep,导致线程空跑,CPU使用率飙升。
示例
启一个线程一直在死循环
#include <iostream>
#include <thread>
using namespace std;
void loopThread()
{
while(true)
{
}
}
int main()
{
thread t1(loopThread);
t1.detach();
sleep(1000);
}
g++ cpu cpu.cpp -o -g
查看CPU使用情况
可以看到CPU使用率已经到了100%
在while死循环里加上usleep
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
void loopThread()
{
while(true)
{
usleep(5);
}
}
int main()
{
thread t1(loopThread);
t1.detach();
sleep(1000);
}
再次查看CPU使用率
发现CPU已经降下来了。