-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHandlerThread.h
99 lines (80 loc) · 2.38 KB
/
HandlerThread.h
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
#ifndef HANDLERTHREAD_H_
#define HANDLERTHREAD_H_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <queue>
class HandlerThread {
private:
using Task = std::function<void()>;
public:
HandlerThread(): mForceQuit(false), mSafeQuit(false) {
mWorker = std::thread([&](){
while(true) {
Task task;
{
std::unique_lock<std::mutex> lock(mEnqueueLock);
mTaskCond.wait(lock,[&](){return !mTaskQueue.empty()|| mForceQuit || mSafeQuit;});
if(mTaskQueue.empty() || mForceQuit) {
return ;
}
task = mTaskQueue.front();
mTaskQueue.pop();
}
task();
}
});
}
template<typename F, typename... Args>
auto enqueue(F && f, Args &&... args) -> std::shared_future<decltype(f(args...))> {
using RType = decltype(f(args...));
std::function<RType()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
auto task_ptr = std::make_shared<std::packaged_task<RType()>>(func);
std::function<void()> threadFunc = [task_ptr]() {
(*task_ptr)();
return ;
};
{
std::lock_guard<std::mutex> lock(mEnqueueLock);
mTaskQueue.push(threadFunc);
mTaskCond.notify_one();
}
return task_ptr->get_future();
}
void quit() {
{
std::lock_guard<std::mutex> lock(mEnqueueLock);
mSafeQuit = true;
}
mTaskCond.notify_one();
if(mWorker.joinable()) {
mWorker.join();
}
}
void quitSafely() {
{
std::lock_guard<std::mutex> lock(mEnqueueLock);
mForceQuit = true;
}
mTaskCond.notify_one();
if(mWorker.joinable()) {
mWorker.join();
}
}
~HandlerThread() {
quit();
}
private:
HandlerThread(const HandlerThread &) = delete;
HandlerThread& operator=(const HandlerThread &) = delete;
private:
bool mForceQuit;
bool mSafeQuit;
std::thread mWorker;
std::mutex mEnqueueLock;
std::condition_variable mTaskCond;
std::queue<Task> mTaskQueue;
};
#endif