-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathWorker.hpp
94 lines (72 loc) · 1.62 KB
/
Worker.hpp
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
#pragma once
#include <chrono>
#include <future>
#include <list>
#include <memory>
#include <thread>
template <class T>
using worker_list_t = std::list<std::unique_ptr<T>>;
class WorkerBase {
public:
WorkerBase() {
_stop_requested_future = _stop_requested.get_future();
}
virtual ~WorkerBase() {}
void run() {
if (!_thread.joinable()) {
_thread = std::thread(&WorkerBase::_workerMain, this);
}
}
std::thread& thread() {
return _thread;
}
std::thread::id threadId() {
return _thread.get_id();
}
bool stopRequested() {
if (_stop_requested_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout) {
return false;
}
return true;
}
void stop() {
_stop_requested.set_value();
}
private:
std::thread _thread;
std::promise<void> _stop_requested;
std::future<void> _stop_requested_future;
protected:
virtual void _workerMain() {}
};
template <class T>
class WorkerGroup {
public:
WorkerGroup<T>() {}
~WorkerGroup<T>() {}
using iterator = typename worker_list_t<T>::iterator;
void addWorker(T* worker) {
_workers.push_back(std::unique_ptr<T>(worker));
worker->run();
}
void killAndDeleteAll() {
for (auto& wrk : _workers) {
if (wrk->thread().joinable()) {
wrk->stop();
wrk->thread().join();
}
}
_workers.clear();
}
worker_list_t<T>& getWorkerList() {
return _workers;
}
typename worker_list_t<T>::iterator begin() {
return _workers.begin();
}
typename worker_list_t<T>::iterator end() {
return _workers.end();
}
private:
worker_list_t<T> _workers;
};