-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityWorker.h
More file actions
112 lines (91 loc) · 2.54 KB
/
PriorityWorker.h
File metadata and controls
112 lines (91 loc) · 2.54 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
105
106
107
108
109
110
111
112
#pragma once
#include <thread>
#include <functional>
#include "Semaphore.h"
struct PriorityTask {
PriorityTask(const std::shared_ptr<std::function<void()>> &function,
size_t priority) : toRun(function),
priority(priority) {}
std::shared_ptr<std::function<void()>> toRun;
size_t priority;
bool operator<(const PriorityTask &b) const {
return priority < b.priority;
}
};
enum WorkerState {
IDLE, RUNNING, STOPPED
};
class PriorityWorker {
public:
PriorityWorker(const size_t &id) : id(id) {
mainThread = workerThread();
}
~PriorityWorker() {
if (mainThread.joinable()) {
join();
}
}
void assignTask(const std::shared_ptr<PriorityTask> &task) {
currentTask = task;
runTask();
}
const size_t getId() {
return id;
}
void stop() {
state = STOPPED;
mainSemaphore.unlock();
}
void join() {
mainThread.join();
}
void detach() {
mainThread.detach();
}
void onIdle(const std::shared_ptr<std::function<void(PriorityWorker *worker)>> &callback) {
onIdleCallback = callback;
}
void onStop(const std::shared_ptr<std::function<void(PriorityWorker *worker)>> &callback) {
onStopCallback = callback;
}
WorkerState state = IDLE;
private:
const std::size_t id;
std::thread workerThread() {
return std::thread([&] {
while (state != STOPPED) {
mainSemaphore.lock();
if (currentTask == nullptr) {
continue;
}
if (state == STOPPED) {
fireStopCallback();
return;
}
currentTask->toRun->operator()();
currentTask = nullptr;
state = IDLE;
fireIdleCallback();
}
});
}
void runTask() {
state = RUNNING;
mainSemaphore.unlock();
}
void fireStopCallback() {
if (onStopCallback != nullptr) {
onStopCallback->operator()(this);
}
}
void fireIdleCallback() {
if (onIdleCallback != nullptr) {
onIdleCallback->operator()(this);
}
}
Semaphore mainSemaphore;
std::thread mainThread;
std::shared_ptr<PriorityTask> currentTask;
std::shared_ptr<std::function<void(PriorityWorker *worker)>> onIdleCallback;
std::shared_ptr<std::function<void(PriorityWorker *worker)>> onStopCallback;
};