-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.cpp
More file actions
69 lines (60 loc) · 988 Bytes
/
Timer.cpp
File metadata and controls
69 lines (60 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "Timer.h"
#include <iostream>
Timer::Timer()
{
mSwitch = false;
mQuit = false;
mUpdatePeroidMs = 1000;
mJobs.clear();
}
Timer::~Timer()
{
mQuit = true;
this->turnOff();
if (mThread.joinable())
{
mThread.join();
std::cout << "mThread joined." << std::endl;
}
else
{
std::cout << "mTread is unjoinable, detach it." << std::endl;
mThread.detach();
}
std::cout << "Timer deleted." << std::endl;
}
void Timer::turnOn()
{
mSwitch = true;
if (!mThread.joinable())
{
mThread = std::thread([&] {
uint16_t round = 1;
for (;;)
{
if (mQuit)
{
std::cout << "Timer on quit." << std::endl;
return;
}
if (mSwitch)
{
std::cout << "Job round: " << round++ << std::endl;
for (auto j : mJobs)
{
j();
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(mUpdatePeroidMs));
}
});
}
}
void Timer::turnOff()
{
mSwitch = false;
}
void Timer::addJob(Job job)
{
mJobs.push_back(job);
}