11#include " CpuMonitor.hpp"
22
3- CpuMonitor::CpuMonitor (int durationTimeToCheckMS, bool &isMonitoringEnable ) : durationTimeToCheckMS(durationTimeToCheckMS), isMonitoringEnable(isMonitoringEnable), lastCpuUsage(0.0 ) {}
3+ CpuMonitor::CpuMonitor (int durationTimeToCheckMS) : durationTimeToCheckMS(durationTimeToCheckMS), lastCpuUsage(0.0 ), monitoringCpuStatus( false ) {}
44
55/* *
66 * @brief Starts monitoring the CPU usage.
@@ -18,6 +18,14 @@ CpuMonitor::CpuMonitor(int durationTimeToCheckMS, bool &isMonitoringEnable) : du
1818 */
1919void CpuMonitor::startMonitoring ()
2020{
21+ // if monitoring enabled
22+ if (this ->monitoringCpuStatus )
23+ {
24+ return ;
25+ }
26+
27+ // if monitoring disabled
28+ this ->monitoringCpuStatus = true ;
2129 monitorThread = std::thread (&CpuMonitor::thread_getCPUUsage, this );
2230 monitorThread.detach (); // Detach the thread so it runs in the background
2331}
@@ -95,15 +103,8 @@ void CpuMonitor::readCpuTimes(long long &user, long long &nice, long long &syste
95103 */
96104void CpuMonitor::thread_getCPUUsage ()
97105{
98- while (true )
106+ while (this -> monitoringCpuStatus )
99107 {
100- // if monitoring disable
101- if (!this ->isMonitoringEnable )
102- {
103- std::this_thread::sleep_for (std::chrono::milliseconds (1000 ));
104- continue ;
105- }
106-
107108 long long user1, nice1, system1, idle1;
108109 long long user2, nice2, system2, idle2;
109110
@@ -133,3 +134,20 @@ void CpuMonitor::thread_getCPUUsage()
133134 std::this_thread::sleep_for (std::chrono::milliseconds (this ->durationTimeToCheckMS ));
134135 }
135136}
137+
138+ /* *
139+ * @brief Stops the CPU monitoring process.
140+ *
141+ * This function sets the `monitoringCpuStatus` flag to `false`,
142+ * indicating that the CPU monitoring should be stopped. Any ongoing
143+ * monitoring activities will cease, and the system will no longer
144+ * collect or process CPU usage data.
145+ *
146+ * This method should be called when monitoring is no longer needed
147+ * to ensure that resources are released and the monitoring process
148+ * is gracefully terminated.
149+ */
150+ void CpuMonitor::stopMonitoring ()
151+ {
152+ this ->monitoringCpuStatus = false ;
153+ }
0 commit comments