-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathutil_internal_thread.cpp
More file actions
104 lines (86 loc) · 2.16 KB
/
util_internal_thread.cpp
File metadata and controls
104 lines (86 loc) · 2.16 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*!
* \brief Internal Thread.
* Mainly implemented by thread.
*/
#include <iostream>
#include <thread>
class InternalThread {
public:
InternalThread();
virtual ~InternalThread();
bool StartInnerThread();
void StopInnerThread();
// To chech wether the internal thread has been started.
bool is_started() const;
protected:
// Virtual function, should be override by the classes
// which needs a internal thread to assist.
virtual void EntryInnerThread() {}
bool must_stop();
private:
bool interrupt_flag_;
std::shared_ptr<std::thread> thread_;
};
InternalThread::InternalThread()
: thread_(), interrupt_flag_(false) {}
InternalThread::~InternalThread() {
StopInnerThread();
}
inline bool InternalThread::is_started() const {
return thread_ && thread_->joinable();
}
bool InternalThread::must_stop() {
if (thread_ && interrupt_flag_) {
interrupt_flag_ = false;
return true;
}
else
return false;
}
bool InternalThread::StartInnerThread() {
if (is_started()) {
printf("Threads should persist and not be restarted.");
return false;
}
try {
thread_.reset(new std::thread(&InternalThread::EntryInnerThread, this));
}
catch (std::exception& e) {
printf("Thread exception: %s", e.what());
}
return true;
}
void InternalThread::StopInnerThread() {
if (is_started()) {
// This flag will work in must_stop.
interrupt_flag_ = true;
try {
thread_->join();
}
catch (std::exception& e) {
printf("Thread exception: %s", e.what());
}
}
}
////////////////////// Test //////////////////////////////
class InternalThreadTest : public InternalThread {
private:
void EntryInnerThread() {
while (!must_stop()) {
std::cout << "0";
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
}
};
int main() {
InternalThreadTest test;
bool ret = test.StartInnerThread();
std::cout << "Start: " << ((ret == true) ? "Succeeded" : "Failed") << std::endl;
for (int i = 0; i < 100; i++) {
std::cout << "1";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::cout << std::endl << "End." << std::endl;
test.StopInnerThread();
return 0;
}