Skip to content

Commit

Permalink
Merge pull request #7 from ivanmari/master
Browse files Browse the repository at this point in the history
Thread safety. Thread safe flag, using positive logic.
  • Loading branch information
shalithasuranga authored Apr 15, 2021
2 parents 17aa021 + ee3347c commit fbf9110
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
4 changes: 2 additions & 2 deletions sample.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using namespace std;

int main() {
Timer t = Timer();
Timer t;

t.setInterval([&]() {
cout << "Hey.. After each 1s..." << endl;
Expand All @@ -21,4 +21,4 @@ int main() {


while(true); // Keep mail thread active
}
}
22 changes: 11 additions & 11 deletions timercpp.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>

class Timer {
bool clear = false;

std::atomic<bool> active{true};
public:
void setTimeout(auto function, int delay);
void setInterval(auto function, int interval);
Expand All @@ -13,29 +14,28 @@ 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();
}
});
t.detach();
}

void Timer::stop() {
this->clear = true;
}
active = false;
}

0 comments on commit fbf9110

Please sign in to comment.