Coverage Report

Created: 2025-09-16 07:56

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