今天朋友問我一個Linux程序CPU占用漲停了,該如何分析,
CPU占用過高,模擬CPU占用過高的情況
先上一段代碼:
1 #include <iostream>
2 #include <thread>
3 #include <vector>
4
5
6 int main(int argc, char **argv) { 7
8 std::vector<std::thread> test_threads; 9 for(int i = 0; i < 9; i++){ 10 test_threads.push_back(std::thread([]{ 11 while(1){ 12 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 13 } 14 })); 15 } 16 test_threads.push_back(std::thread([]{ 17 while(1){ 18 std::cout<<"cpu"<<std::endl; 19 } 20 })); 21
22 for(auto &x : test_threads){ 23 x.join(); 24 } 25
26 return 0; 27 }
第10個線程中沒有進行睡眠,會獨占進程的時間片,導致CPU利用率過高,
現在就要定位到第10個
第一步:top 查看程序進程id

第二步:top -H -p 96263 定位CPU占用過高的線程id

第三步:使用pstack 96263或者strace -f -p 96263 定位線程堆棧
strace -f -p 96263

