/root/doris/be/src/util/threadpool.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | // This file is copied from |
18 | | // https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/threadpool.cc |
19 | | // and modified by Doris |
20 | | |
21 | | #include "util/threadpool.h" |
22 | | |
23 | | #include <algorithm> |
24 | | #include <cstdint> |
25 | | #include <limits> |
26 | | #include <ostream> |
27 | | #include <thread> |
28 | | #include <utility> |
29 | | |
30 | | #include "absl/strings/substitute.h" |
31 | | #include "common/exception.h" |
32 | | #include "common/logging.h" |
33 | | #include "util/debug_points.h" |
34 | | #include "util/doris_metrics.h" |
35 | | #include "util/metrics.h" |
36 | | #include "util/scoped_cleanup.h" |
37 | | #include "util/stopwatch.hpp" |
38 | | #include "util/thread.h" |
39 | | |
40 | | namespace doris { |
41 | | // The name of these varialbs will be useds as metric name in prometheus. |
42 | | DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_active_threads, MetricUnit::NOUNIT); |
43 | | DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_queue_size, MetricUnit::NOUNIT); |
44 | | DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_max_queue_size, MetricUnit::NOUNIT); |
45 | | DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_max_threads, MetricUnit::NOUNIT); |
46 | | DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_submit_failed, MetricUnit::NOUNIT); |
47 | | DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_execution_time_ns_total, |
48 | | MetricUnit::NANOSECONDS); |
49 | | DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_execution_count_total, MetricUnit::NOUNIT); |
50 | | DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_wait_worker_time_ns_total, |
51 | | MetricUnit::NANOSECONDS); |
52 | | DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_wait_worker_count_total, MetricUnit::NOUNIT); |
53 | | using namespace ErrorCode; |
54 | | |
55 | | using std::string; |
56 | | |
57 | | class FunctionRunnable : public Runnable { |
58 | | public: |
59 | 8.43k | explicit FunctionRunnable(std::function<void()> func) : _func(std::move(func)) {} |
60 | | |
61 | 4.69k | void run() override { _func(); } |
62 | | |
63 | | private: |
64 | | std::function<void()> _func; |
65 | | }; |
66 | | |
67 | | ThreadPoolBuilder::ThreadPoolBuilder(string name, string workload_group) |
68 | | : _name(std::move(name)), |
69 | | _workload_group(std::move(workload_group)), |
70 | | _min_threads(0), |
71 | | _max_threads(std::thread::hardware_concurrency()), |
72 | | _max_queue_size(std::numeric_limits<int>::max()), |
73 | 329 | _idle_timeout(std::chrono::milliseconds(500)) {} |
74 | | |
75 | 293 | ThreadPoolBuilder& ThreadPoolBuilder::set_min_threads(int min_threads) { |
76 | 293 | CHECK_GE(min_threads, 0); |
77 | 293 | _min_threads = min_threads; |
78 | 293 | return *this; |
79 | 293 | } |
80 | | |
81 | 301 | ThreadPoolBuilder& ThreadPoolBuilder::set_max_threads(int max_threads) { |
82 | 301 | CHECK_GT(max_threads, 0); |
83 | 301 | _max_threads = max_threads; |
84 | 301 | return *this; |
85 | 301 | } |
86 | | |
87 | 96 | ThreadPoolBuilder& ThreadPoolBuilder::set_max_queue_size(int max_queue_size) { |
88 | 96 | _max_queue_size = max_queue_size; |
89 | 96 | return *this; |
90 | 96 | } |
91 | | |
92 | | ThreadPoolBuilder& ThreadPoolBuilder::set_cgroup_cpu_ctl( |
93 | 1 | std::weak_ptr<CgroupCpuCtl> cgroup_cpu_ctl) { |
94 | 1 | _cgroup_cpu_ctl = cgroup_cpu_ctl; |
95 | 1 | return *this; |
96 | 1 | } |
97 | | |
98 | | ThreadPoolToken::ThreadPoolToken(ThreadPool* pool, ThreadPool::ExecutionMode mode, |
99 | | int max_concurrency) |
100 | | : _mode(mode), |
101 | | _pool(pool), |
102 | | _state(State::IDLE), |
103 | | _active_threads(0), |
104 | | _max_concurrency(max_concurrency), |
105 | | _num_submitted_tasks(0), |
106 | 2.30k | _num_unsubmitted_tasks(0) { |
107 | 2.30k | if (max_concurrency == 1 && mode != ThreadPool::ExecutionMode::SERIAL) { |
108 | 1 | _mode = ThreadPool::ExecutionMode::SERIAL; |
109 | 1 | } |
110 | 2.30k | } |
111 | | |
112 | 2.29k | ThreadPoolToken::~ThreadPoolToken() { |
113 | 2.29k | shutdown(); |
114 | 2.29k | _pool->release_token(this); |
115 | 2.29k | } |
116 | | |
117 | 7.06k | Status ThreadPoolToken::submit(std::shared_ptr<Runnable> r) { |
118 | 7.06k | return _pool->do_submit(std::move(r), this); |
119 | 7.06k | } |
120 | | |
121 | 7.08k | Status ThreadPoolToken::submit_func(std::function<void()> f) { |
122 | 7.08k | return submit(std::make_shared<FunctionRunnable>(std::move(f))); |
123 | 7.08k | } |
124 | | |
125 | 3.41k | void ThreadPoolToken::shutdown() { |
126 | 3.41k | std::unique_lock<std::mutex> l(_pool->_lock); |
127 | 3.41k | _pool->check_not_pool_thread_unlocked(); |
128 | | |
129 | | // Clear the queue under the lock, but defer the releasing of the tasks |
130 | | // outside the lock, in case there are concurrent threads wanting to access |
131 | | // the ThreadPool. The task's destructors may acquire locks, etc, so this |
132 | | // also prevents lock inversions. |
133 | 3.41k | std::deque<ThreadPool::Task> to_release = std::move(_entries); |
134 | 3.41k | _pool->_total_queued_tasks -= to_release.size(); |
135 | | |
136 | 3.41k | switch (state()) { |
137 | 1.02k | case State::IDLE: |
138 | | // There were no tasks outstanding; we can quiesce the token immediately. |
139 | 1.02k | transition(State::QUIESCED); |
140 | 1.02k | break; |
141 | 955 | case State::RUNNING: |
142 | | // There were outstanding tasks. If any are still running, switch to |
143 | | // QUIESCING and wait for them to finish (the worker thread executing |
144 | | // the token's last task will switch the token to QUIESCED). Otherwise, |
145 | | // we can quiesce the token immediately. |
146 | | |
147 | | // Note: this is an O(n) operation, but it's expected to be infrequent. |
148 | | // Plus doing it this way (rather than switching to QUIESCING and waiting |
149 | | // for a worker thread to process the queue entry) helps retain state |
150 | | // transition symmetry with ThreadPool::shutdown. |
151 | 7.70k | for (auto it = _pool->_queue.begin(); it != _pool->_queue.end();) { |
152 | 6.75k | if (*it == this) { |
153 | 711 | it = _pool->_queue.erase(it); |
154 | 6.04k | } else { |
155 | 6.04k | it++; |
156 | 6.04k | } |
157 | 6.75k | } |
158 | | |
159 | 955 | if (_active_threads == 0) { |
160 | 350 | transition(State::QUIESCED); |
161 | 350 | break; |
162 | 350 | } |
163 | 605 | transition(State::QUIESCING); |
164 | 605 | [[fallthrough]]; |
165 | 618 | case State::QUIESCING: |
166 | | // The token is already quiescing. Just wait for a worker thread to |
167 | | // switch it to QUIESCED. |
168 | 1.23k | _not_running_cond.wait(l, [this]() { return state() == State::QUIESCED; }); |
169 | 618 | break; |
170 | 1.42k | default: |
171 | 1.42k | break; |
172 | 3.41k | } |
173 | 3.41k | } |
174 | | |
175 | 838 | void ThreadPoolToken::wait() { |
176 | 838 | std::unique_lock<std::mutex> l(_pool->_lock); |
177 | 838 | _pool->check_not_pool_thread_unlocked(); |
178 | 1.05k | _not_running_cond.wait(l, [this]() { return !is_active(); }); |
179 | 838 | } |
180 | | |
181 | 7.81k | void ThreadPoolToken::transition(State new_state) { |
182 | 7.81k | #ifndef NDEBUG |
183 | 7.81k | CHECK_NE(_state, new_state); |
184 | | |
185 | 7.81k | switch (_state) { |
186 | 4.26k | case State::IDLE: |
187 | 4.26k | CHECK(new_state == State::RUNNING || new_state == State::QUIESCED); |
188 | 4.26k | if (new_state == State::RUNNING) { |
189 | 2.93k | CHECK(!_entries.empty()); |
190 | 2.93k | } else { |
191 | 1.33k | CHECK(_entries.empty()); |
192 | 1.33k | CHECK_EQ(_active_threads, 0); |
193 | 1.33k | } |
194 | 4.26k | break; |
195 | 2.93k | case State::RUNNING: |
196 | 2.93k | CHECK(new_state == State::IDLE || new_state == State::QUIESCING || |
197 | 2.93k | new_state == State::QUIESCED); |
198 | 2.93k | CHECK(_entries.empty()); |
199 | 2.93k | if (new_state == State::QUIESCING) { |
200 | 612 | CHECK_GT(_active_threads, 0); |
201 | 612 | } |
202 | 2.93k | break; |
203 | 612 | case State::QUIESCING: |
204 | 612 | CHECK(new_state == State::QUIESCED); |
205 | 612 | CHECK_EQ(_active_threads, 0); |
206 | 612 | break; |
207 | 0 | case State::QUIESCED: |
208 | 0 | CHECK(false); // QUIESCED is a terminal state |
209 | 0 | break; |
210 | 0 | default: |
211 | 0 | throw Exception(Status::FatalError("Unknown token state: {}", _state)); |
212 | 7.81k | } |
213 | 7.81k | #endif |
214 | | |
215 | | // Take actions based on the state we're entering. |
216 | 7.81k | switch (new_state) { |
217 | 1.97k | case State::IDLE: |
218 | 4.26k | case State::QUIESCED: |
219 | 4.26k | _not_running_cond.notify_all(); |
220 | 4.26k | break; |
221 | 3.54k | default: |
222 | 3.54k | break; |
223 | 7.81k | } |
224 | | |
225 | 7.81k | _state = new_state; |
226 | 7.81k | } |
227 | | |
228 | 0 | const char* ThreadPoolToken::state_to_string(State s) { |
229 | 0 | switch (s) { |
230 | 0 | case State::IDLE: |
231 | 0 | return "IDLE"; |
232 | 0 | break; |
233 | 0 | case State::RUNNING: |
234 | 0 | return "RUNNING"; |
235 | 0 | break; |
236 | 0 | case State::QUIESCING: |
237 | 0 | return "QUIESCING"; |
238 | 0 | break; |
239 | 0 | case State::QUIESCED: |
240 | 0 | return "QUIESCED"; |
241 | 0 | break; |
242 | 0 | } |
243 | 0 | return "<cannot reach here>"; |
244 | 0 | } |
245 | | |
246 | 6.31k | bool ThreadPoolToken::need_dispatch() { |
247 | 6.31k | return _state == ThreadPoolToken::State::IDLE || |
248 | 6.31k | (_mode == ThreadPool::ExecutionMode::CONCURRENT && |
249 | 3.38k | _num_submitted_tasks < _max_concurrency); |
250 | 6.31k | } |
251 | | |
252 | | ThreadPool::ThreadPool(const ThreadPoolBuilder& builder) |
253 | | : _name(builder._name), |
254 | | _workload_group(builder._workload_group), |
255 | | _min_threads(builder._min_threads), |
256 | | _max_threads(builder._max_threads), |
257 | | _max_queue_size(builder._max_queue_size), |
258 | | _idle_timeout(builder._idle_timeout), |
259 | | _pool_status(Status::Uninitialized("The pool was not initialized.")), |
260 | | _num_threads(0), |
261 | | _num_threads_pending_start(0), |
262 | | _active_threads(0), |
263 | | _total_queued_tasks(0), |
264 | | _cgroup_cpu_ctl(builder._cgroup_cpu_ctl), |
265 | | _tokenless(new_token(ExecutionMode::CONCURRENT)), |
266 | 324 | _id(UniqueId::gen_uid()) {} |
267 | | |
268 | 312 | ThreadPool::~ThreadPool() { |
269 | | // There should only be one live token: the one used in tokenless submission. |
270 | 312 | CHECK_EQ(1, _tokens.size()) << absl::Substitute( |
271 | 0 | "Threadpool $0 destroyed with $1 allocated tokens", _name, _tokens.size()); |
272 | 312 | shutdown(); |
273 | 312 | } |
274 | | |
275 | 329 | Status ThreadPool::try_create_thread(int thread_num, std::lock_guard<std::mutex>&) { |
276 | 1.36k | for (int i = 0; i < thread_num; i++) { |
277 | 1.03k | Status status = create_thread(); |
278 | 1.03k | if (status.ok()) { |
279 | 1.03k | _num_threads_pending_start++; |
280 | 1.03k | } else { |
281 | 0 | LOG(WARNING) << "Thread pool " << _name << " failed to create thread: " << status; |
282 | 0 | return status; |
283 | 0 | } |
284 | 1.03k | } |
285 | 329 | return Status::OK(); |
286 | 329 | } |
287 | | |
288 | 324 | Status ThreadPool::init() { |
289 | 324 | if (!_pool_status.is<UNINITIALIZED>()) { |
290 | 0 | return Status::NotSupported("The thread pool {} is already initialized", _name); |
291 | 0 | } |
292 | 324 | _pool_status = Status::OK(); |
293 | | |
294 | 324 | { |
295 | 324 | std::lock_guard<std::mutex> l(_lock); |
296 | | // create thread failed should not cause threadpool init failed, |
297 | | // because thread can be created later such as when submit a task. |
298 | 324 | static_cast<void>(try_create_thread(_min_threads, l)); |
299 | 324 | } |
300 | | |
301 | | // _id of thread pool is used to make sure when we create thread pool with same name, we can |
302 | | // get different _metric_entity |
303 | | // If not, we will have problem when we deregister entity and register hook. |
304 | 324 | _metric_entity = DorisMetrics::instance()->metric_registry()->register_entity( |
305 | 324 | fmt::format("thread_pool_{}", _name), {{"thread_pool_name", _name}, |
306 | 324 | {"workload_group", _workload_group}, |
307 | 324 | {"id", _id.to_string()}}); |
308 | | |
309 | 324 | INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_active_threads); |
310 | 324 | INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_threads); |
311 | 324 | INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_queue_size); |
312 | 324 | INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_queue_size); |
313 | 324 | INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_time_ns_total); |
314 | 324 | INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_count_total); |
315 | 324 | INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_time_ns_total); |
316 | 324 | INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_count_total); |
317 | 324 | INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_submit_failed); |
318 | | |
319 | 324 | _metric_entity->register_hook("update", [this]() { |
320 | 0 | { |
321 | 0 | std::lock_guard<std::mutex> l(_lock); |
322 | 0 | if (!_pool_status.ok()) { |
323 | 0 | return; |
324 | 0 | } |
325 | 0 | } |
326 | | |
327 | 0 | thread_pool_active_threads->set_value(num_active_threads()); |
328 | 0 | thread_pool_queue_size->set_value(get_queue_size()); |
329 | 0 | thread_pool_max_queue_size->set_value(get_max_queue_size()); |
330 | 0 | thread_pool_max_threads->set_value(max_threads()); |
331 | 0 | }); |
332 | 324 | return Status::OK(); |
333 | 324 | } |
334 | | |
335 | 536 | void ThreadPool::shutdown() { |
336 | | // Why access to doris_metrics is safe here? |
337 | | // Since DorisMetrics is a singleton, it will be destroyed only after doris_main is exited. |
338 | | // The shutdown/destroy of ThreadPool is guaranteed to take place before doris_main exits by |
339 | | // ExecEnv::destroy(). |
340 | 536 | DorisMetrics::instance()->metric_registry()->deregister_entity(_metric_entity); |
341 | 536 | std::unique_lock<std::mutex> l(_lock); |
342 | 536 | check_not_pool_thread_unlocked(); |
343 | | |
344 | | // Note: this is the same error seen at submission if the pool is at |
345 | | // capacity, so clients can't tell them apart. This isn't really a practical |
346 | | // concern though because shutting down a pool typically requires clients to |
347 | | // be quiesced first, so there's no danger of a client getting confused. |
348 | | // Not print stack trace here |
349 | 536 | _pool_status = Status::Error<SERVICE_UNAVAILABLE, false>( |
350 | 536 | "The thread pool {} has been shut down.", _name); |
351 | | |
352 | | // Clear the various queues under the lock, but defer the releasing |
353 | | // of the tasks outside the lock, in case there are concurrent threads |
354 | | // wanting to access the ThreadPool. The task's destructors may acquire |
355 | | // locks, etc, so this also prevents lock inversions. |
356 | 536 | _queue.clear(); |
357 | | |
358 | 536 | std::deque<std::deque<Task>> to_release; |
359 | 538 | for (auto* t : _tokens) { |
360 | 538 | if (!t->_entries.empty()) { |
361 | 3 | to_release.emplace_back(std::move(t->_entries)); |
362 | 3 | } |
363 | 538 | switch (t->state()) { |
364 | 307 | case ThreadPoolToken::State::IDLE: |
365 | | // The token is idle; we can quiesce it immediately. |
366 | 307 | t->transition(ThreadPoolToken::State::QUIESCED); |
367 | 307 | break; |
368 | 7 | case ThreadPoolToken::State::RUNNING: |
369 | | // The token has tasks associated with it. If they're merely queued |
370 | | // (i.e. there are no active threads), the tasks will have been removed |
371 | | // above and we can quiesce immediately. Otherwise, we need to wait for |
372 | | // the threads to finish. |
373 | 7 | t->transition(t->_active_threads > 0 ? ThreadPoolToken::State::QUIESCING |
374 | 7 | : ThreadPoolToken::State::QUIESCED); |
375 | 7 | break; |
376 | 224 | default: |
377 | 224 | break; |
378 | 538 | } |
379 | 538 | } |
380 | | |
381 | | // The queues are empty. Wake any sleeping worker threads and wait for all |
382 | | // of them to exit. Some worker threads will exit immediately upon waking, |
383 | | // while others will exit after they finish executing an outstanding task. |
384 | 536 | _total_queued_tasks = 0; |
385 | 1.63k | while (!_idle_threads.empty()) { |
386 | 1.10k | _idle_threads.front().not_empty.notify_one(); |
387 | 1.10k | _idle_threads.pop_front(); |
388 | 1.10k | } |
389 | | |
390 | 826 | _no_threads_cond.wait(l, [this]() { return _num_threads + _num_threads_pending_start == 0; }); |
391 | | |
392 | | // All the threads have exited. Check the state of each token. |
393 | 538 | for (auto* t : _tokens) { |
394 | 538 | DCHECK(t->state() == ThreadPoolToken::State::IDLE || |
395 | 538 | t->state() == ThreadPoolToken::State::QUIESCED); |
396 | 538 | } |
397 | 536 | } |
398 | | |
399 | 2.30k | std::unique_ptr<ThreadPoolToken> ThreadPool::new_token(ExecutionMode mode, int max_concurrency) { |
400 | 2.30k | std::lock_guard<std::mutex> l(_lock); |
401 | 2.30k | std::unique_ptr<ThreadPoolToken> t(new ThreadPoolToken(this, mode, max_concurrency)); |
402 | 2.30k | if (!_tokens.insert(t.get()).second) { |
403 | 0 | throw Exception(Status::InternalError("duplicate token")); |
404 | 0 | } |
405 | 2.30k | return t; |
406 | 2.30k | } |
407 | | |
408 | 2.29k | void ThreadPool::release_token(ThreadPoolToken* t) { |
409 | 2.29k | std::lock_guard<std::mutex> l(_lock); |
410 | 2.29k | CHECK(!t->is_active()) << absl::Substitute("Token with state $0 may not be released", |
411 | 0 | ThreadPoolToken::state_to_string(t->state())); |
412 | 2.29k | CHECK_EQ(1, _tokens.erase(t)); |
413 | 2.29k | } |
414 | | |
415 | 1.60k | Status ThreadPool::submit(std::shared_ptr<Runnable> r) { |
416 | 1.60k | return do_submit(std::move(r), _tokenless.get()); |
417 | 1.60k | } |
418 | | |
419 | 1.36k | Status ThreadPool::submit_func(std::function<void()> f) { |
420 | 1.36k | return submit(std::make_shared<FunctionRunnable>(std::move(f))); |
421 | 1.36k | } |
422 | | |
423 | 8.72k | Status ThreadPool::do_submit(std::shared_ptr<Runnable> r, ThreadPoolToken* token) { |
424 | 8.72k | DCHECK(token); |
425 | | |
426 | 8.72k | std::unique_lock<std::mutex> l(_lock); |
427 | 8.72k | if (PREDICT_FALSE(!_pool_status.ok())) { |
428 | 1 | return _pool_status; |
429 | 1 | } |
430 | | |
431 | 8.72k | if (PREDICT_FALSE(!token->may_submit_new_tasks())) { |
432 | 2.41k | return Status::Error<SERVICE_UNAVAILABLE>("Thread pool({}) token was shut down", _name); |
433 | 2.41k | } |
434 | | |
435 | | // Size limit check. |
436 | 6.31k | int64_t capacity_remaining = static_cast<int64_t>(_max_threads) - _active_threads + |
437 | 6.31k | static_cast<int64_t>(_max_queue_size) - _total_queued_tasks; |
438 | 6.31k | if (capacity_remaining < 1) { |
439 | 4 | thread_pool_submit_failed->increment(1); |
440 | 4 | return Status::Error<SERVICE_UNAVAILABLE>( |
441 | 4 | "Thread pool {} is at capacity ({}/{} tasks running, {}/{} tasks queued)", _name, |
442 | 4 | _num_threads + _num_threads_pending_start, _max_threads, _total_queued_tasks, |
443 | 4 | _max_queue_size); |
444 | 4 | } |
445 | | |
446 | | // Should we create another thread? |
447 | | |
448 | | // We assume that each current inactive thread will grab one item from the |
449 | | // queue. If it seems like we'll need another thread, we create one. |
450 | | // |
451 | | // Rather than creating the thread here, while holding the lock, we defer |
452 | | // it to down below. This is because thread creation can be rather slow |
453 | | // (hundreds of milliseconds in some cases) and we'd like to allow the |
454 | | // existing threads to continue to process tasks while we do so. |
455 | | // |
456 | | // In theory, a currently active thread could finish immediately after this |
457 | | // calculation but before our new worker starts running. This would mean we |
458 | | // created a thread we didn't really need. However, this race is unavoidable |
459 | | // and harmless. |
460 | | // |
461 | | // Of course, we never create more than _max_threads threads no matter what. |
462 | 6.30k | int threads_from_this_submit = |
463 | 6.30k | token->is_active() && token->mode() == ExecutionMode::SERIAL ? 0 : 1; |
464 | 6.30k | int inactive_threads = _num_threads + _num_threads_pending_start - _active_threads; |
465 | 6.30k | int additional_threads = |
466 | 6.30k | static_cast<int>(_queue.size()) + threads_from_this_submit - inactive_threads; |
467 | 6.30k | bool need_a_thread = false; |
468 | 6.30k | if (additional_threads > 0 && _num_threads + _num_threads_pending_start < _max_threads) { |
469 | 625 | need_a_thread = true; |
470 | 625 | _num_threads_pending_start++; |
471 | 625 | } |
472 | | |
473 | 6.30k | Task task; |
474 | 6.30k | task.runnable = std::move(r); |
475 | 6.30k | task.submit_time_wather.start(); |
476 | | |
477 | | // Add the task to the token's queue. |
478 | 6.30k | ThreadPoolToken::State state = token->state(); |
479 | 6.30k | DCHECK(state == ThreadPoolToken::State::IDLE || state == ThreadPoolToken::State::RUNNING); |
480 | 6.30k | token->_entries.emplace_back(std::move(task)); |
481 | | // When we need to execute the task in the token, we submit the token object to the queue. |
482 | | // There are currently two places where tokens will be submitted to the queue: |
483 | | // 1. When submitting a new task, if the token is still in the IDLE state, |
484 | | // or the concurrency of the token has not reached the online level, it will be added to the queue. |
485 | | // 2. When the dispatch thread finishes executing a task: |
486 | | // 1. If it is a SERIAL token, and there are unsubmitted tasks, submit them to the queue. |
487 | | // 2. If it is a CONCURRENT token, and there are still unsubmitted tasks, and the upper limit of concurrency is not reached, |
488 | | // then submitted to the queue. |
489 | 6.30k | if (token->need_dispatch()) { |
490 | 4.93k | _queue.emplace_back(token); |
491 | 4.93k | ++token->_num_submitted_tasks; |
492 | 4.93k | if (state == ThreadPoolToken::State::IDLE) { |
493 | 2.93k | token->transition(ThreadPoolToken::State::RUNNING); |
494 | 2.93k | } |
495 | 4.93k | } else { |
496 | 1.37k | ++token->_num_unsubmitted_tasks; |
497 | 1.37k | } |
498 | 6.30k | _total_queued_tasks++; |
499 | | |
500 | | // Wake up an idle thread for this task. Choosing the thread at the front of |
501 | | // the list ensures LIFO semantics as idling threads are also added to the front. |
502 | | // |
503 | | // If there are no idle threads, the new task remains on the queue and is |
504 | | // processed by an active thread (or a thread we're about to create) at some |
505 | | // point in the future. |
506 | 6.30k | if (!_idle_threads.empty()) { |
507 | 1.93k | _idle_threads.front().not_empty.notify_one(); |
508 | 1.93k | _idle_threads.pop_front(); |
509 | 1.93k | } |
510 | 6.30k | l.unlock(); |
511 | | |
512 | 6.30k | if (need_a_thread) { |
513 | 625 | Status status = create_thread(); |
514 | 625 | if (!status.ok()) { |
515 | 0 | l.lock(); |
516 | 0 | _num_threads_pending_start--; |
517 | 0 | if (_num_threads + _num_threads_pending_start == 0) { |
518 | | // If we have no threads, we can't do any work. |
519 | 0 | return status; |
520 | 0 | } |
521 | | // If we failed to create a thread, but there are still some other |
522 | | // worker threads, log a warning message and continue. |
523 | 0 | LOG(WARNING) << "Thread pool " << _name |
524 | 0 | << " failed to create thread: " << status.to_string(); |
525 | 0 | } |
526 | 625 | } |
527 | | |
528 | 6.30k | return Status::OK(); |
529 | 6.30k | } |
530 | | |
531 | 124 | void ThreadPool::wait() { |
532 | 124 | std::unique_lock<std::mutex> l(_lock); |
533 | 124 | check_not_pool_thread_unlocked(); |
534 | 250 | _idle_cond.wait(l, [this]() { return _total_queued_tasks == 0 && _active_threads == 0; }); |
535 | 124 | } |
536 | | |
537 | 1.66k | void ThreadPool::dispatch_thread() { |
538 | 1.66k | std::unique_lock<std::mutex> l(_lock); |
539 | 1.66k | if (!_threads.insert(Thread::current_thread()).second) { |
540 | 0 | throw Exception(Status::InternalError("duplicate token")); |
541 | 0 | } |
542 | 1.66k | DCHECK_GT(_num_threads_pending_start, 0); |
543 | 1.66k | _num_threads++; |
544 | 1.66k | _num_threads_pending_start--; |
545 | | |
546 | 1.66k | if (std::shared_ptr<CgroupCpuCtl> cg_cpu_ctl_sptr = _cgroup_cpu_ctl.lock()) { |
547 | 0 | static_cast<void>(cg_cpu_ctl_sptr->add_thread_to_cgroup()); |
548 | 0 | } |
549 | | |
550 | | // Owned by this worker thread and added/removed from _idle_threads as needed. |
551 | 1.66k | IdleThread me; |
552 | | |
553 | 276k | while (true) { |
554 | | // Note: Status::Aborted() is used to indicate normal shutdown. |
555 | 276k | if (!_pool_status.ok()) { |
556 | 1.13k | VLOG_CRITICAL << "DispatchThread exiting: " << _pool_status.to_string(); |
557 | 1.13k | break; |
558 | 1.13k | } |
559 | | |
560 | 275k | if (_num_threads + _num_threads_pending_start > _max_threads) { |
561 | 2 | break; |
562 | 2 | } |
563 | | |
564 | 275k | if (_queue.empty()) { |
565 | | // There's no work to do, let's go idle. |
566 | | // |
567 | | // Note: if FIFO behavior is desired, it's as simple as changing this to push_back(). |
568 | 271k | _idle_threads.push_front(me); |
569 | 271k | SCOPED_CLEANUP({ |
570 | | // For some wake ups (i.e. shutdown or do_submit) this thread is |
571 | | // guaranteed to be unlinked after being awakened. In others (i.e. |
572 | | // spurious wake-up or Wait timeout), it'll still be linked. |
573 | 271k | if (me.is_linked()) { |
574 | 271k | _idle_threads.erase(_idle_threads.iterator_to(me)); |
575 | 271k | } |
576 | 271k | }); |
577 | 271k | if (me.not_empty.wait_for(l, _idle_timeout) == std::cv_status::timeout) { |
578 | | // After much investigation, it appears that pthread condition variables have |
579 | | // a weird behavior in which they can return ETIMEDOUT from timed_wait even if |
580 | | // another thread did in fact signal. Apparently after a timeout there is some |
581 | | // brief period during which another thread may actually grab the internal mutex |
582 | | // protecting the state, signal, and release again before we get the mutex. So, |
583 | | // we'll recheck the empty queue case regardless. |
584 | 268k | if (_queue.empty() && _num_threads + _num_threads_pending_start > _min_threads) { |
585 | 507 | VLOG_NOTICE << "Releasing worker thread from pool " << _name << " after " |
586 | 0 | << std::chrono::duration_cast<std::chrono::milliseconds>( |
587 | 0 | _idle_timeout) |
588 | 0 | .count() |
589 | 0 | << "ms of idle time."; |
590 | 507 | break; |
591 | 507 | } |
592 | 268k | } |
593 | 270k | continue; |
594 | 271k | } |
595 | | |
596 | 4.25k | MonotonicStopWatch task_execution_time_watch; |
597 | 4.25k | task_execution_time_watch.start(); |
598 | | // Get the next token and task to execute. |
599 | 4.25k | ThreadPoolToken* token = _queue.front(); |
600 | 4.25k | _queue.pop_front(); |
601 | 4.25k | DCHECK_EQ(ThreadPoolToken::State::RUNNING, token->state()); |
602 | 4.25k | DCHECK(!token->_entries.empty()); |
603 | 4.25k | Task task = std::move(token->_entries.front()); |
604 | 4.25k | thread_pool_task_wait_worker_time_ns_total->increment( |
605 | 4.25k | task.submit_time_wather.elapsed_time()); |
606 | 4.25k | thread_pool_task_wait_worker_count_total->increment(1); |
607 | 4.25k | token->_entries.pop_front(); |
608 | 4.25k | token->_active_threads++; |
609 | 4.25k | --_total_queued_tasks; |
610 | 4.25k | ++_active_threads; |
611 | | |
612 | 4.25k | l.unlock(); |
613 | | |
614 | | // Execute the task |
615 | 4.25k | task.runnable->run(); |
616 | | // Destruct the task while we do not hold the lock. |
617 | | // |
618 | | // The task's destructor may be expensive if it has a lot of bound |
619 | | // objects, and we don't want to block submission of the threadpool. |
620 | | // In the worst case, the destructor might even try to do something |
621 | | // with this threadpool, and produce a deadlock. |
622 | 4.25k | task.runnable.reset(); |
623 | 4.25k | l.lock(); |
624 | 4.25k | thread_pool_task_execution_time_ns_total->increment( |
625 | 4.25k | task_execution_time_watch.elapsed_time()); |
626 | 4.25k | thread_pool_task_execution_count_total->increment(1); |
627 | | // Possible states: |
628 | | // 1. The token was shut down while we ran its task. Transition to QUIESCED. |
629 | | // 2. The token has no more queued tasks. Transition back to IDLE. |
630 | | // 3. The token has more tasks. Requeue it and transition back to RUNNABLE. |
631 | 4.25k | ThreadPoolToken::State state = token->state(); |
632 | 4.25k | DCHECK(state == ThreadPoolToken::State::RUNNING || |
633 | 4.25k | state == ThreadPoolToken::State::QUIESCING); |
634 | 4.25k | --token->_active_threads; |
635 | 4.25k | --token->_num_submitted_tasks; |
636 | | |
637 | | // handle shutdown && idle |
638 | 4.25k | if (token->_active_threads == 0) { |
639 | 3.48k | if (state == ThreadPoolToken::State::QUIESCING) { |
640 | 612 | DCHECK(token->_entries.empty()); |
641 | 612 | token->transition(ThreadPoolToken::State::QUIESCED); |
642 | 2.87k | } else if (token->_entries.empty()) { |
643 | 1.97k | token->transition(ThreadPoolToken::State::IDLE); |
644 | 1.97k | } |
645 | 3.48k | } |
646 | | |
647 | | // We decrease _num_submitted_tasks holding lock, so the following DCHECK works. |
648 | 4.25k | DCHECK(token->_num_submitted_tasks < token->_max_concurrency); |
649 | | |
650 | | // If token->state is running and there are unsubmitted tasks in the token, we put |
651 | | // the token back. |
652 | 4.25k | if (token->_num_unsubmitted_tasks > 0 && state == ThreadPoolToken::State::RUNNING) { |
653 | | // SERIAL: if _entries is not empty, then num_unsubmitted_tasks must be greater than 0. |
654 | | // CONCURRENT: we have to check _num_unsubmitted_tasks because there may be at least 2 |
655 | | // threads are running for the token. |
656 | 739 | _queue.emplace_back(token); |
657 | 739 | ++token->_num_submitted_tasks; |
658 | 739 | --token->_num_unsubmitted_tasks; |
659 | 739 | } |
660 | | |
661 | 4.25k | if (--_active_threads == 0) { |
662 | 940 | _idle_cond.notify_all(); |
663 | 940 | } |
664 | 4.25k | } |
665 | | |
666 | | // It's important that we hold the lock between exiting the loop and dropping |
667 | | // _num_threads. Otherwise it's possible someone else could come along here |
668 | | // and add a new task just as the last running thread is about to exit. |
669 | 1.66k | CHECK(l.owns_lock()); |
670 | | |
671 | 1.66k | CHECK_EQ(_threads.erase(Thread::current_thread()), 1); |
672 | 1.66k | _num_threads--; |
673 | 1.66k | if (_num_threads + _num_threads_pending_start == 0) { |
674 | 789 | _no_threads_cond.notify_all(); |
675 | | |
676 | | // Sanity check: if we're the last thread exiting, the queue ought to be |
677 | | // empty. Otherwise it will never get processed. |
678 | 789 | CHECK(_queue.empty()); |
679 | 789 | DCHECK_EQ(0, _total_queued_tasks); |
680 | 789 | } |
681 | 1.66k | } |
682 | | |
683 | 1.66k | Status ThreadPool::create_thread() { |
684 | 1.66k | return Thread::create("thread pool", absl::Substitute("$0 [worker]", _name), |
685 | 1.66k | &ThreadPool::dispatch_thread, this, nullptr); |
686 | 1.66k | } |
687 | | |
688 | 4.91k | void ThreadPool::check_not_pool_thread_unlocked() { |
689 | 4.91k | Thread* current = Thread::current_thread(); |
690 | 4.91k | if (_threads.contains(current)) { |
691 | 0 | throw Exception( |
692 | 0 | Status::FatalError("Thread belonging to thread pool {} with " |
693 | 0 | "name {} called pool function that would result in deadlock", |
694 | 0 | _name, current->name())); |
695 | 0 | } |
696 | 4.91k | } |
697 | | |
698 | 4 | Status ThreadPool::set_min_threads(int min_threads) { |
699 | 4 | std::lock_guard<std::mutex> l(_lock); |
700 | 4 | if (min_threads > _max_threads) { |
701 | | // min threads can not be set greater than max threads |
702 | 1 | return Status::InternalError("set thread pool {} min_threads failed", _name); |
703 | 1 | } |
704 | 3 | _min_threads = min_threads; |
705 | 3 | if (min_threads > _num_threads + _num_threads_pending_start) { |
706 | 0 | int addition_threads = min_threads - _num_threads - _num_threads_pending_start; |
707 | 0 | RETURN_IF_ERROR(try_create_thread(addition_threads, l)); |
708 | 0 | } |
709 | 3 | return Status::OK(); |
710 | 3 | } |
711 | | |
712 | 8 | Status ThreadPool::set_max_threads(int max_threads) { |
713 | 8 | std::lock_guard<std::mutex> l(_lock); |
714 | 8 | DBUG_EXECUTE_IF("ThreadPool.set_max_threads.force_set", { |
715 | 8 | _max_threads = max_threads; |
716 | 8 | return Status::OK(); |
717 | 8 | }) |
718 | 8 | if (_min_threads > max_threads) { |
719 | | // max threads can not be set less than min threads |
720 | 1 | return Status::InternalError("set thread pool {} max_threads failed", _name); |
721 | 1 | } |
722 | | |
723 | 7 | _max_threads = max_threads; |
724 | 7 | if (_max_threads > _num_threads + _num_threads_pending_start) { |
725 | 5 | int addition_threads = _max_threads - _num_threads - _num_threads_pending_start; |
726 | 5 | addition_threads = std::min(addition_threads, _total_queued_tasks); |
727 | 5 | RETURN_IF_ERROR(try_create_thread(addition_threads, l)); |
728 | 5 | } |
729 | 7 | return Status::OK(); |
730 | 7 | } |
731 | | |
732 | 0 | std::ostream& operator<<(std::ostream& o, ThreadPoolToken::State s) { |
733 | 0 | return o << ThreadPoolToken::state_to_string(s); |
734 | 0 | } |
735 | | |
736 | | } // namespace doris |