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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
|
#include "lix/libutil/thread-pool.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/signals.hh"
#include "lix/libutil/thread-name.hh"
#include <kj/common.h>
namespace nix {
ThreadPool::ThreadPool(const char * name, size_t _maxThreads)
: maxThreads(_maxThreads), name(name)
{
if (!maxThreads) {
maxThreads = std::thread::hardware_concurrency();
if (!maxThreads) maxThreads = 1;
}
debug("starting pool of %d threads", maxThreads);
}
ThreadPool::~ThreadPool()
{
shutdown();
}
void ThreadPool::shutdown()
{
std::vector<std::thread> workers;
{
auto state(state_.lock());
quit = true;
std::swap(workers, state->workers);
}
if (workers.empty()) return;
debug("reaping %d worker threads", workers.size());
work.notify_all();
for (auto & thr : workers)
thr.join();
}
void ThreadPool::enqueueWithAio(const work_t & t)
{
auto state(state_.lock());
if (quit)
throw ThreadPoolShutDown("cannot enqueue a work item while the thread pool is shutting down");
state->pending.push(t);
if (state->active == state->workers.size() && state->workers.size() < maxThreads)
state->workers.emplace_back(&ThreadPool::doWork, this);
work.notify_one();
}
void ThreadPool::process()
{
const auto shouldWait = [&] {
auto state(state_.lock());
state->draining = true;
return state->active > 0 || !state->pending.empty();
}();
/* Wait until no more work is pending or active. */
try {
if (shouldWait) {
quit.wait(false);
}
auto state(state_.lock());
if (state->exception)
std::rethrow_exception(state->exception);
} catch (...) {
/* In the exceptional case, some workers may still be
active. They may be referencing the stack frame of the
caller. So wait for them to finish. (~ThreadPool also does
this, but it might be destroyed after objects referenced by
the work item lambdas.) */
shutdown();
throw;
}
}
kj::Promise<Result<void>> ThreadPool::processAsync()
try {
auto [shouldWait, signal] = [&] {
auto state = state_.lock();
state->draining = true;
auto pfp = kj::newPromiseAndCrossThreadFulfiller<void>();
state->anyWorkerExited = std::move(pfp.fulfiller);
return std::pair(state->active > 0 || !state->pending.empty(), std::move(pfp.promise));
}();
KJ_DEFER({
if (std::uncaught_exceptions()) {
/* In the exceptional case, some workers may still be
active. They may be referencing the stack frame of the
caller. So wait for them to finish. (~ThreadPool also does
this, but it might be destroyed after objects referenced by
the work item lambdas.) */
shutdown();
}
});
/* Wait until no more work is pending or active. */
if (shouldWait && !quit) {
co_await signal;
}
auto state(state_.lock());
if (state->exception) {
std::rethrow_exception(state->exception);
}
co_return result::success();
} catch (...) {
co_return result::current_exception();
}
void ThreadPool::doWork()
{
// Tell the other workers to quit; we only return on errors or completion
KJ_DEFER({
quit = true;
quit.notify_all();
if (auto state = state_.lock(); state->anyWorkerExited) {
(*state->anyWorkerExited)->fulfill();
state->anyWorkerExited.reset();
}
work.notify_all();
});
ReceiveInterrupts receiveInterrupts;
setCurrentThreadName(this->name);
interruptCheck = [&]() { return (bool) quit; };
bool didWork = false;
std::exception_ptr exc;
AsyncIoRoot aio;
while (true) {
work_t w;
{
auto state(state_.lock());
if (didWork) {
assert(state->active);
state->active--;
if (exc) {
if (!state->exception) {
state->exception = exc;
return;
} else {
/* Print the exception, since we can't
propagate it. */
try {
std::rethrow_exception(exc);
} catch (ThreadPoolShutDown &) {
} catch (...) {
// Yes, this is not a destructor, but we cannot
// safely propagate an exception out of here.
//
// What happens is that if we do, shutdown()
// will have join() throw an exception if we
// are on a worker thread, preventing us from
// joining the rest of the threads. Although we
// could make the joining eat exceptions too,
// we could just as well not let Interrupted
// fall out to begin with, since the thread
// will immediately cleanly quit because of
// quit == true anyway.
ignoreExceptionInDestructor();
}
}
}
}
/* Wait until a work item is available or we're asked to
quit. */
while (true) {
if (quit) return;
if (!state->pending.empty()) break;
/* If there are no active or pending items, and the
main thread is running process(), then no new items
can be added. So exit. */
if (!state->active && state->draining) {
return;
}
state.wait(work);
}
w = std::move(state->pending.front());
state->pending.pop();
state->active++;
}
try {
w(aio);
} catch (...) {
exc = std::current_exception();
}
didWork = true;
}
}
}
|