diff --git a/sample.cpp b/sample.cpp index 58b61e5..435b0c9 100644 --- a/sample.cpp +++ b/sample.cpp @@ -4,7 +4,7 @@ using namespace std; int main() { - Timer t = Timer(); + Timer t; t.setInterval([&]() { cout << "Hey.. After each 1s..." << endl; @@ -21,4 +21,4 @@ int main() { while(true); // Keep mail thread active -} \ No newline at end of file +} diff --git a/timercpp.h b/timercpp.h index 46d3226..c97e3c9 100644 --- a/timercpp.h +++ b/timercpp.h @@ -1,10 +1,11 @@ #include #include #include +#include class Timer { - bool clear = false; - + std::atomic active{true}; + public: void setTimeout(auto function, int delay); void setInterval(auto function, int interval); @@ -13,23 +14,22 @@ class Timer { }; void Timer::setTimeout(auto function, int delay) { - this->clear = false; + active = true; std::thread t([=]() { - if(this->clear) return; + if(!active.load()) return; std::this_thread::sleep_for(std::chrono::milliseconds(delay)); - if(this->clear) return; + if(!active.load()) return; function(); }); t.detach(); } void Timer::setInterval(auto function, int interval) { - this->clear = false; + active = true; std::thread t([=]() { - while(true) { - if(this->clear) return; + while(active.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(interval)); - if(this->clear) return; + if(!active.load()) return; function(); } }); @@ -37,5 +37,5 @@ void Timer::setInterval(auto function, int interval) { } void Timer::stop() { - this->clear = true; -} \ No newline at end of file + active = false; +}