![](https://img.haomeiwen.com/i12856594/f603cee1eb5515a5.jpg)
在Linux开发中经常会与多线程打交道,所以多线程开发与调试就很重要
下边说下Linux调试过程中CPU占用率过高的情况怎么调试
CPU占用过高,模拟CPU占用过高的情况
先上一段代码:
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char **argv) {
std::vector<std::thread> test_threads;
for(int i = 0; i < 9; i++){
test_threads.push_back(std::thread([]{
while(1){
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}));
}
test_threads.push_back(std::thread([]{
while(1){
std::cout<<"cpu"<<std::endl;
}
}));
for(auto &x : test_threads){
x.join();
}
return 0;
}
用下边的命令编译( linux标准库没有pthread.h 要链接之-lpthread):
g++ -o allen_test allen_test.cpp -lpthread
执行可执行文件:
./allen_test
由代码可知,线程中没有进行睡眠,会独占进程的时间片,导致CPU利用率过高,现在开始定位
第一步:使用top命令查看程序进程id
![](https://img.haomeiwen.com/i12856594/65bcc38b161a1cc3.gif)
第二步:top -H -p 33401 定位CPU占用过高的线程id
![](https://img.haomeiwen.com/i12856594/72ab0b98eee1cfb7.jpg)
第三步:strace -p33411定位线程堆栈
![](https://img.haomeiwen.com/i12856594/f988e6b91f6e5f57.png)
2020年7月21日 晚
我的首发平台是微信公号【CodeAllen】,喜欢的小伙伴欢迎关注并回复“1024”获取资料
网友评论