11#include " MemoryMonitor.hpp"
22
3- MemoryMonitor::MemoryMonitor (int durationTimeToCheckMS, bool &isMonitoringEnable )
4- : durationTimeToCheckMS(durationTimeToCheckMS), isMonitoringEnable(isMonitoringEnable), lastMemoryUsage(0.0 ) {}
3+ MemoryMonitor::MemoryMonitor (int durationTimeToCheckMS)
4+ : durationTimeToCheckMS(durationTimeToCheckMS), lastMemoryUsage(0.0 ), monitoringMemoryStatus( false ) {}
55
66/* *
77 * @brief Starts monitoring memory usage by launching a background thread.
@@ -30,6 +30,14 @@ MemoryMonitor::MemoryMonitor(int durationTimeToCheckMS, bool &isMonitoringEnable
3030 */
3131void MemoryMonitor::startMonitoring ()
3232{
33+ // if monitoring enabled
34+ if (this ->monitoringMemoryStatus )
35+ {
36+ return ;
37+ }
38+
39+ // if monitoring disabled
40+ this ->monitoringMemoryStatus = true ;
3341 monitorThread = std::thread (&MemoryMonitor::thread_getMemoryUsage, this );
3442 monitorThread.detach (); // Detach the thread so it runs in the background
3543}
@@ -94,15 +102,8 @@ double MemoryMonitor::getLastMemoryUsage() const
94102 */
95103void MemoryMonitor::thread_getMemoryUsage ()
96104{
97- while (true )
105+ while (this -> monitoringMemoryStatus )
98106 {
99- // if monitoring disable
100- if (!this ->isMonitoringEnable )
101- {
102- std::this_thread::sleep_for (std::chrono::milliseconds (1000 ));
103- continue ;
104- }
105-
106107 std::ifstream memInfoFile (" /proc/meminfo" );
107108 if (!memInfoFile.is_open ())
108109 {
@@ -152,3 +153,20 @@ void MemoryMonitor::thread_getMemoryUsage()
152153 std::this_thread::sleep_for (std::chrono::milliseconds (this ->durationTimeToCheckMS ));
153154 }
154155}
156+
157+ /* *
158+ * @brief Stops the memory monitoring process.
159+ *
160+ * This function sets the `monitoringMemoryStatus` flag to `false`,
161+ * indicating that memory monitoring should be stopped. As a result,
162+ * any ongoing memory usage tracking will cease, and the system will
163+ * no longer collect or process memory usage data.
164+ *
165+ * It is essential to call this method when memory monitoring is
166+ * no longer required to free up resources and ensure the monitoring
167+ * process is gracefully terminated.
168+ */
169+ void MemoryMonitor::stopMonitoring ()
170+ {
171+ this ->monitoringMemoryStatus = false ;
172+ }
0 commit comments