blob: 45fb6df9a9412c5306fb1a285a40b3bb0f415b67 (
plain)
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
|
#include "worker.h"
#include <algorithm>
#include <iterator>
#include <mutex>
Worker Worker::instance;
Worker::Worker() : todoLen {0}
{
std::generate_n(std::back_inserter(threads), std::thread::hardware_concurrency(), [this]() {
return std::jthread {&Worker::worker, this};
});
}
Worker::~Worker()
{
todoLen.release(std::thread::hardware_concurrency());
}
void
Worker::addWorkPtr(WorkPtr j)
{
std::lock_guard<std::mutex> lck {todoMutex};
todoLen.release();
todo.emplace_back(std::move(j));
}
void
Worker::worker()
{
auto job = [this]() {
todoLen.acquire();
std::lock_guard<std::mutex> lck {todoMutex};
if (todo.size()) {
WorkPtr x = std::move(todo.front());
todo.pop_front();
return x;
}
return WorkPtr {};
};
while (auto j = job()) {
j->doWork();
}
}
void
Worker::assist()
{
auto job = [this]() {
using namespace std::chrono_literals;
if (todoLen.try_acquire_for(100us)) {
if (std::lock_guard<std::mutex> lck {todoMutex}; todo.size()) {
WorkPtr x = std::move(todo.front());
if (x) {
todo.pop_front();
}
return x;
}
}
return WorkPtr {};
};
if (auto j = job()) {
j->doWork();
}
}
|