Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- };
Add Comment
Please, Sign In to add comment