Coverage Report

Created: 2026-07-14 15:37

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