Skip to content

Instantly share code, notes, and snippets.

@zzxx-husky
Created December 13, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzxx-husky/eab15e2876ae392706c8501cbd5290b4 to your computer and use it in GitHub Desktop.
Save zzxx-husky/eab15e2876ae392706c8501cbd5290b4 to your computer and use it in GitHub Desktop.
#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