File tree Expand file tree Collapse file tree 2 files changed +13
-13
lines changed Expand file tree Collapse file tree 2 files changed +13
-13
lines changed Original file line number Diff line number Diff line change 4
4
using namespace std ;
5
5
6
6
int main () {
7
- Timer t = Timer () ;
7
+ Timer t;
8
8
9
9
t.setInterval ([&]() {
10
10
cout << " Hey.. After each 1s..." << endl;
@@ -21,4 +21,4 @@ int main() {
21
21
22
22
23
23
while (true ); // Keep mail thread active
24
- }
24
+ }
Original file line number Diff line number Diff line change 1
1
#include < iostream>
2
2
#include < thread>
3
3
#include < chrono>
4
+ #include < atomic>
4
5
5
6
class Timer {
6
- bool clear = false ;
7
-
7
+ std::atomic< bool > active{ true } ;
8
+
8
9
public:
9
10
void setTimeout (auto function, int delay);
10
11
void setInterval (auto function, int interval);
@@ -13,29 +14,28 @@ class Timer {
13
14
};
14
15
15
16
void Timer::setTimeout (auto function, int delay) {
16
- this -> clear = false ;
17
+ active = true ;
17
18
std::thread t ([=]() {
18
- if (this -> clear ) return ;
19
+ if (!active. load () ) return ;
19
20
std::this_thread::sleep_for (std::chrono::milliseconds (delay));
20
- if (this -> clear ) return ;
21
+ if (!active. load () ) return ;
21
22
function ();
22
23
});
23
24
t.detach ();
24
25
}
25
26
26
27
void Timer::setInterval (auto function, int interval) {
27
- this -> clear = false ;
28
+ active = true ;
28
29
std::thread t ([=]() {
29
- while (true ) {
30
- if (this ->clear ) return ;
30
+ while (active.load ()) {
31
31
std::this_thread::sleep_for (std::chrono::milliseconds (interval));
32
- if (this -> clear ) return ;
32
+ if (!active. load () ) return ;
33
33
function ();
34
34
}
35
35
});
36
36
t.detach ();
37
37
}
38
38
39
39
void Timer::stop () {
40
- this -> clear = true ;
41
- }
40
+ active = false ;
41
+ }
You can’t perform that action at this time.
0 commit comments