Today, my friend asked me a Linux program CPU consumption limit, how to analyze,
High CPU consumption, simulating high CPU usage
The first piece of code:
1#include <iostream>2#include <thread>3#include <vector>4 5 6 intMainintargcChar**argv) {7 8Std::vector<std::thread>test_threads;9 for(inti =0; I <9; i++){Ten Test_threads.push_back (Std::thread ([]{ One while(1){ AStd::this_thread::sleep_for (Std::chrono::milliseconds ( -)); - } - })); the } - Test_threads.push_back (Std::thread ([]{ - while(1){ -std::cout<<"CPU"<<Std::endl; + } - })); + A for(Auto &x:test_threads) { at X.join (); - } - - return 0; -}
The 10th thread does not sleep, it will monopolize the process of the time slice, resulting in high CPU utilization,
Now we need to locate 10th.
First step: Top View program Process ID
Step two: Top-h-P 96263 locates CPU-intensive thread IDs
Step three: Use Pstack 96263 or strace-f-P 96263 to locate the thread stack
Strace-f-P 96263
Linux threads occupy high CPU location analysis