Skip to content

Commit fbf9110

Browse files
Merge pull request #7 from ivanmari/master
Thread safety. Thread safe flag, using positive logic.
2 parents 17aa021 + ee3347c commit fbf9110

File tree

2 files changed

+13
-13
lines changed

2 files changed

+13
-13
lines changed

sample.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
using namespace std;
55

66
int main() {
7-
Timer t = Timer();
7+
Timer t;
88

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

2222

2323
while(true); // Keep mail thread active
24-
}
24+
}

timercpp.h

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
#include <iostream>
22
#include <thread>
33
#include <chrono>
4+
#include <atomic>
45

56
class Timer {
6-
bool clear = false;
7-
7+
std::atomic<bool> active{true};
8+
89
public:
910
void setTimeout(auto function, int delay);
1011
void setInterval(auto function, int interval);
@@ -13,29 +14,28 @@ class Timer {
1314
};
1415

1516
void Timer::setTimeout(auto function, int delay) {
16-
this->clear = false;
17+
active = true;
1718
std::thread t([=]() {
18-
if(this->clear) return;
19+
if(!active.load()) return;
1920
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
20-
if(this->clear) return;
21+
if(!active.load()) return;
2122
function();
2223
});
2324
t.detach();
2425
}
2526

2627
void Timer::setInterval(auto function, int interval) {
27-
this->clear = false;
28+
active = true;
2829
std::thread t([=]() {
29-
while(true) {
30-
if(this->clear) return;
30+
while(active.load()) {
3131
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
32-
if(this->clear) return;
32+
if(!active.load()) return;
3333
function();
3434
}
3535
});
3636
t.detach();
3737
}
3838

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

0 commit comments

Comments
 (0)