Created
December 13, 2018 14:33
-
-
Save zzxx-husky/eab15e2876ae392706c8501cbd5290b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <chrono> | |
#include <functional> | |
#include <iostream> | |
template<typename I> | |
class StatisticMonitor { | |
public: | |
typedef std::function<I()> Watcher; | |
StatisticMonitor &watch(Watcher tput) { | |
this->current_value = tput; | |
return *this; | |
} | |
StatisticMonitor &set_name(std::string name) { | |
this->name = std::move(name); | |
return *this; | |
} | |
void launch() { | |
if (timer != nullptr) { | |
return; | |
} | |
timer = new std::thread([=]() { | |
while (non_terminated) { | |
std::cout << name << ": " << current_value() << std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); | |
} | |
std::cout << name << " now terminates. " << endl; | |
}); | |
} | |
void terminate() { | |
if (timer != nullptr) { | |
non_terminated = false; | |
timer->join(); | |
delete timer; | |
timer = nullptr; | |
} | |
} | |
private: | |
bool non_terminated = true; | |
std::thread *timer = nullptr; | |
std::string name; | |
Watcher current_value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment