forked from pantyusha/nesca
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreader.cpp
More file actions
56 lines (52 loc) · 1.54 KB
/
Copy pathThreader.cpp
File metadata and controls
56 lines (52 loc) · 1.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
#include "Threader.h"
int Threader::gThreadDelay = 10;
std::atomic<int> Threader::activeThreads(0);
std::mutex Threader::m;
bool Threader::stop = false;
std::condition_variable Threader::cv;
std::queue<std::pair<std::string, std::function<void(std::string)>>> Threader::taskQueue;
std::vector<std::thread> Threader::workers;
void Threader::worker() {
while (true) {
std::pair<std::string, std::function<void(std::string)>> task;
{
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [] { return stop || !taskQueue.empty(); });
if (stop && taskQueue.empty()) return;
task = std::move(taskQueue.front());
taskQueue.pop();
}
activeThreads++;
task.second(task.first);
activeThreads--;
}
}
void Threader::fireThread(std::string ip, void (*func)(std::string)) {
{
std::lock_guard<std::mutex> lock(m);
if (workers.empty()) {
stop = false;
int numThreads = gThreads;
if (numThreads <= 0) numThreads = 1;
for (int i = 0; i < numThreads; ++i) {
workers.emplace_back(worker);
}
}
taskQueue.push({ip, func});
}
cv.notify_one();
}
void Threader::cleanUp() {
{
std::lock_guard<std::mutex> lock(m);
stop = true;
while (!taskQueue.empty()) taskQueue.pop();
}
cv.notify_all();
for (auto& w : workers) {
if (w.joinable()) w.join();
}
workers.clear();
activeThreads = 0;
stop = false;
}