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