-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorker.h
98 lines (81 loc) · 2.12 KB
/
Worker.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
#pragma once
#include <thread>
#include <functional>
#include "Semaphore.h"
enum WorkerState {
IDLE, RUNNING, STOPPED
};
class Worker {
public:
Worker(const size_t &id) : id(id) {
mainThread = workerThread();
}
~Worker() {
if (mainThread.joinable()) {
join();
}
}
void assignTask(std::shared_ptr<std::function<void()>> 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(Worker *worker)>> &callback) {
onIdleCallback = callback;
}
void onStop(const std::shared_ptr<std::function<void(Worker *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->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<std::function<void()>> currentTask;
std::shared_ptr<std::function<void(Worker *worker)>> onIdleCallback;
std::shared_ptr<std::function<void(Worker *worker)>> onStopCallback;
};