Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread safety. Thread safe flag, using positive logic. #7

Merged
merged 1 commit into from
Apr 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}