Coverage Report

Created: 2026-07-15 01:39

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
28.0k
    explicit FunctionRunnable(std::function<void()> func) : _func(std::move(func)) {}
59
60
22.4k
    void run() override { _func(); }
61
62
private:
63
    std::function<void()> _func;
64
};
65
66
ThreadPoolBuilder::ThreadPoolBuilder(string name, string workload_group)
67
892
        : _name(std::move(name)),
68
892
          _workload_group(std::move(workload_group)),
69
892
          _min_threads(0),
70
892
          _max_threads(std::thread::hardware_concurrency()),
71
892
          _max_queue_size(std::numeric_limits<int>::max()),
72
892
          _idle_timeout(std::chrono::milliseconds(500)) {}
73
74
844
ThreadPoolBuilder& ThreadPoolBuilder::set_min_threads(int min_threads) {
75
844
    CHECK_GE(min_threads, 0);
76
844
    _min_threads = min_threads;
77
844
    return *this;
78
844
}
79
80
864
ThreadPoolBuilder& ThreadPoolBuilder::set_max_threads(int max_threads) {
81
864
    CHECK_GT(max_threads, 0);
82
864
    _max_threads = max_threads;
83
864
    return *this;
84
864
}
85
86
128
ThreadPoolBuilder& ThreadPoolBuilder::set_max_queue_size(int max_queue_size) {
87
128
    _max_queue_size = max_queue_size;
88
128
    return *this;
89
128
}
90
91
ThreadPoolBuilder& ThreadPoolBuilder::set_cgroup_cpu_ctl(
92
74
        std::weak_ptr<CgroupCpuCtl> cgroup_cpu_ctl) {
93
74
    _cgroup_cpu_ctl = cgroup_cpu_ctl;
94
74
    return *this;
95
74
}
96
97
ThreadPoolToken::ThreadPoolToken(ThreadPool* pool, ThreadPool::ExecutionMode mode,
98
                                 int max_concurrency)
99
4.63k
        : _mode(mode),
100
4.63k
          _pool(pool),
101
4.63k
          _state(State::IDLE),
102
4.63k
          _active_threads(0),
103
4.63k
          _max_concurrency(max_concurrency),
104
4.63k
          _num_submitted_tasks(0),
105
4.63k
          _num_unsubmitted_tasks(0) {
106
4.63k
    if (max_concurrency == 1 && mode != ThreadPool::ExecutionMode::SERIAL) {
107
17
        _mode = ThreadPool::ExecutionMode::SERIAL;
108
17
    }
109
4.63k
}
110
111
4.43k
ThreadPoolToken::~ThreadPoolToken() {
112
4.43k
    shutdown();
113
4.43k
    _pool->release_token(this);
114
4.43k
}
115
116
18.8k
Status ThreadPoolToken::submit(std::shared_ptr<Runnable> r) {
117
18.8k
    return _pool->do_submit(std::move(r), this);
118
18.8k
}
119
120
18.8k
Status ThreadPoolToken::submit_func(std::function<void()> f) {
121
18.8k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
122
18.8k
}
123
124
6.94k
void ThreadPoolToken::shutdown() {
125
6.94k
    std::unique_lock<std::mutex> l(_pool->_lock);
126
6.94k
    _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
6.94k
    std::deque<ThreadPool::Task> to_release = std::move(_entries);
133
6.94k
    _pool->_total_queued_tasks -= to_release.size();
134
135
6.94k
    switch (state()) {
136
2.74k
    case State::IDLE:
137
        // There were no tasks outstanding; we can quiesce the token immediately.
138
2.74k
        transition(State::QUIESCED);
139
2.74k
        break;
140
1.03k
    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
8.05k
        for (auto it = _pool->_queue.begin(); it != _pool->_queue.end();) {
151
7.02k
            if (*it == this) {
152
589
                it = _pool->_queue.erase(it);
153
6.43k
            } else {
154
6.43k
                it++;
155
6.43k
            }
156
7.02k
        }
157
158
1.03k
        if (_active_threads == 0) {
159
220
            transition(State::QUIESCED);
160
220
            break;
161
220
        }
162
815
        transition(State::QUIESCING);
163
815
        [[fallthrough]];
164
829
    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
829
        break;
169
3.15k
    default:
170
3.15k
        break;
171
6.94k
    }
172
6.94k
}
173
174
2.59k
void ThreadPoolToken::wait() {
175
2.59k
    std::unique_lock<std::mutex> l(_pool->_lock);
176
2.59k
    _pool->check_not_pool_thread_unlocked();
177
2.99k
    _not_running_cond.wait(l, [this]() { return !is_active(); });
178
2.59k
}
179
180
25.0k
void ThreadPoolToken::transition(State new_state) {
181
25.0k
#ifndef NDEBUG
182
25.0k
    CHECK_NE(_state, new_state);
183
184
25.0k
    switch (_state) {
185
13.8k
    case State::IDLE:
186
13.8k
        CHECK(new_state == State::RUNNING || new_state == State::QUIESCED);
187
13.8k
        if (new_state == State::RUNNING) {
188
10.4k
            CHECK(!_entries.empty());
189
10.4k
        } else {
190
3.36k
            CHECK(_entries.empty());
191
3.36k
            CHECK_EQ(_active_threads, 0);
192
3.36k
        }
193
13.8k
        break;
194
10.4k
    case State::RUNNING:
195
10.4k
        CHECK(new_state == State::IDLE || new_state == State::QUIESCING ||
196
10.4k
              new_state == State::QUIESCED);
197
10.4k
        CHECK(_entries.empty());
198
10.4k
        if (new_state == State::QUIESCING) {
199
852
            CHECK_GT(_active_threads, 0);
200
852
        }
201
10.4k
        break;
202
852
    case State::QUIESCING:
203
852
        CHECK(new_state == State::QUIESCED);
204
852
        CHECK_EQ(_active_threads, 0);
205
852
        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
25.0k
    }
212
25.0k
#endif
213
214
    // Take actions based on the state we're entering.
215
25.0k
    switch (new_state) {
216
9.33k
    case State::IDLE:
217
13.7k
    case State::QUIESCED:
218
13.7k
        _not_running_cond.notify_all();
219
13.7k
        break;
220
11.2k
    default:
221
11.2k
        break;
222
25.0k
    }
223
224
25.0k
    _state = new_state;
225
25.0k
}
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
24.5k
bool ThreadPoolToken::need_dispatch() {
246
24.5k
    return _state == ThreadPoolToken::State::IDLE ||
247
24.5k
           (_mode == ThreadPool::ExecutionMode::CONCURRENT &&
248
14.0k
            _num_submitted_tasks < _max_concurrency);
249
24.5k
}
250
251
ThreadPool::ThreadPool(const ThreadPoolBuilder& builder)
252
851
        : _name(builder._name),
253
851
          _workload_group(builder._workload_group),
254
851
          _min_threads(builder._min_threads),
255
851
          _max_threads(builder._max_threads),
256
851
          _max_queue_size(builder._max_queue_size),
257
851
          _idle_timeout(builder._idle_timeout),
258
851
          _pool_status(Status::Uninitialized("The pool was not initialized.")),
259
851
          _num_threads(0),
260
851
          _num_threads_pending_start(0),
261
851
          _active_threads(0),
262
851
          _total_queued_tasks(0),
263
851
          _cgroup_cpu_ctl(builder._cgroup_cpu_ctl),
264
851
          _tokenless(new_token(ExecutionMode::CONCURRENT)),
265
851
          _id(UniqueId::gen_uid()) {}
266
267
656
ThreadPool::~ThreadPool() {
268
    // There should only be one live token: the one used in tokenless submission.
269
656
    CHECK_EQ(1, _tokens.size()) << absl::Substitute(
270
0
            "Threadpool $0 destroyed with $1 allocated tokens", _name, _tokens.size());
271
656
    shutdown();
272
656
    VLOG_DEBUG << fmt::format("Thread pool {} destroyed", _name);
273
656
}
274
275
878
Status ThreadPool::try_create_thread(int thread_num, std::lock_guard<std::mutex>&) {
276
7.87k
    for (int i = 0; i < thread_num; i++) {
277
6.99k
        Status status = create_thread();
278
6.99k
        if (status.ok()) {
279
6.99k
            _num_threads_pending_start++;
280
6.99k
        } else {
281
0
            LOG(WARNING) << "Thread pool " << _name << " failed to create thread: " << status;
282
0
            return status;
283
0
        }
284
6.99k
    }
285
878
    return Status::OK();
286
878
}
287
288
851
Status ThreadPool::init() {
289
851
    if (!_pool_status.is<UNINITIALIZED>()) {
290
0
        return Status::NotSupported("The thread pool {} is already initialized", _name);
291
0
    }
292
851
    _pool_status = Status::OK();
293
294
851
    {
295
851
        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
851
        static_cast<void>(try_create_thread(_min_threads, l));
299
851
    }
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
851
    _metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
305
851
            fmt::format("thread_pool_{}", _name), {{"thread_pool_name", _name},
306
851
                                                   {"workload_group", _workload_group},
307
851
                                                   {"id", _id.to_string()}});
308
309
851
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_active_threads);
310
851
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_threads);
311
851
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_queue_size);
312
851
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_queue_size);
313
851
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_time_ns_total);
314
851
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_count_total);
315
851
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_time_ns_total);
316
851
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_count_total);
317
851
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_submit_failed);
318
319
7.52k
    _metric_entity->register_hook("update", [this]() {
320
7.52k
        {
321
7.52k
            std::lock_guard<std::mutex> l(_lock);
322
7.52k
            if (!_pool_status.ok()) {
323
0
                return;
324
0
            }
325
7.52k
        }
326
327
7.52k
        thread_pool_active_threads->set_value(num_active_threads());
328
7.52k
        thread_pool_queue_size->set_value(get_queue_size());
329
7.52k
        thread_pool_max_queue_size->set_value(get_max_queue_size());
330
7.52k
        thread_pool_max_threads->set_value(max_threads());
331
7.52k
    });
332
851
    LOG(INFO) << fmt::format(
333
851
            "Thread pool '{}' initialized: min_threads={}, max_threads={}, max_queue_size={}, "
334
851
            "idle_timeout_ms={}, workload_group='{}'",
335
851
            _name, _min_threads, _max_threads, _max_queue_size, _idle_timeout.count(),
336
851
            _workload_group);
337
851
    return Status::OK();
338
851
}
339
340
1.19k
void ThreadPool::shutdown() {
341
1.19k
    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.19k
    DorisMetrics::instance()->metric_registry()->deregister_entity(_metric_entity);
347
1.19k
    std::unique_lock<std::mutex> l(_lock);
348
1.19k
    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.19k
    _pool_status = Status::Error<SERVICE_UNAVAILABLE, false>(
356
1.19k
            "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.19k
    _queue.clear();
363
364
1.19k
    std::deque<std::deque<Task>> to_release;
365
1.19k
    for (auto* t : _tokens) {
366
1.19k
        if (!t->_entries.empty()) {
367
3
            to_release.emplace_back(std::move(t->_entries));
368
3
        }
369
1.19k
        switch (t->state()) {
370
621
        case ThreadPoolToken::State::IDLE:
371
            // The token is idle; we can quiesce it immediately.
372
621
            t->transition(ThreadPoolToken::State::QUIESCED);
373
621
            break;
374
37
        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
37
            t->transition(t->_active_threads > 0 ? ThreadPoolToken::State::QUIESCING
380
37
                                                 : ThreadPoolToken::State::QUIESCED);
381
37
            break;
382
537
        default:
383
537
            break;
384
1.19k
        }
385
1.19k
    }
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.19k
    _total_queued_tasks = 0;
391
4.94k
    while (!_idle_threads.empty()) {
392
3.75k
        _idle_threads.front().not_empty.notify_one();
393
3.75k
        _idle_threads.pop_front();
394
3.75k
    }
395
396
1.80k
    _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.19k
    for (auto* t : _tokens) {
400
1.19k
        DCHECK(t->state() == ThreadPoolToken::State::IDLE ||
401
1.19k
               t->state() == ThreadPoolToken::State::QUIESCED);
402
1.19k
    }
403
1.19k
}
404
405
4.63k
std::unique_ptr<ThreadPoolToken> ThreadPool::new_token(ExecutionMode mode, int max_concurrency) {
406
4.63k
    std::lock_guard<std::mutex> l(_lock);
407
4.63k
    std::unique_ptr<ThreadPoolToken> t(new ThreadPoolToken(this, mode, max_concurrency));
408
4.63k
    if (!_tokens.insert(t.get()).second) {
409
0
        throw Exception(Status::InternalError("duplicate token"));
410
0
    }
411
4.63k
    return t;
412
4.63k
}
413
414
4.43k
void ThreadPool::release_token(ThreadPoolToken* t) {
415
4.43k
    std::lock_guard<std::mutex> l(_lock);
416
4.43k
    CHECK(!t->is_active()) << absl::Substitute("Token with state $0 may not be released",
417
0
                                               ThreadPoolToken::state_to_string(t->state()));
418
4.43k
    CHECK_EQ(1, _tokens.erase(t));
419
4.43k
}
420
421
9.61k
Status ThreadPool::submit(std::shared_ptr<Runnable> r) {
422
9.61k
    return do_submit(std::move(r), _tokenless.get());
423
9.61k
}
424
425
9.21k
Status ThreadPool::submit_func(std::function<void()> f) {
426
9.21k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
427
9.21k
}
428
429
28.4k
Status ThreadPool::do_submit(std::shared_ptr<Runnable> r, ThreadPoolToken* token) {
430
28.4k
    DCHECK(token);
431
432
28.4k
    std::unique_lock<std::mutex> l(_lock);
433
28.4k
    if (!_pool_status.ok()) [[unlikely]] {
434
1
        return _pool_status;
435
1
    }
436
437
28.4k
    if (!token->may_submit_new_tasks()) [[unlikely]] {
438
4.03k
        return Status::Error<SERVICE_UNAVAILABLE>("Thread pool({}) token was shut down", _name);
439
4.03k
    }
440
441
    // Size limit check.
442
24.4k
    int64_t capacity_remaining = static_cast<int64_t>(_max_threads) - _active_threads +
443
24.4k
                                 static_cast<int64_t>(_max_queue_size) - _total_queued_tasks;
444
24.4k
    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
24.4k
    int threads_from_this_submit =
469
24.4k
            token->is_active() && token->mode() == ExecutionMode::SERIAL ? 0 : 1;
470
24.4k
    int inactive_threads = _num_threads + _num_threads_pending_start - _active_threads;
471
24.4k
    int additional_threads =
472
24.4k
            static_cast<int>(_queue.size()) + threads_from_this_submit - inactive_threads;
473
24.4k
    bool need_a_thread = false;
474
24.4k
    if (additional_threads > 0 && _num_threads + _num_threads_pending_start < _max_threads) {
475
763
        need_a_thread = true;
476
763
        _num_threads_pending_start++;
477
763
    }
478
479
24.4k
    Task task;
480
24.4k
    task.runnable = std::move(r);
481
24.4k
    task.submit_time_wather.start();
482
483
    // Add the task to the token's queue.
484
24.4k
    ThreadPoolToken::State state = token->state();
485
24.4k
    DCHECK(state == ThreadPoolToken::State::IDLE || state == ThreadPoolToken::State::RUNNING);
486
24.4k
    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
24.4k
    if (token->need_dispatch()) {
496
20.3k
        _queue.emplace_back(token);
497
20.3k
        ++token->_num_submitted_tasks;
498
20.3k
        if (state == ThreadPoolToken::State::IDLE) {
499
10.4k
            token->transition(ThreadPoolToken::State::RUNNING);
500
10.4k
        }
501
20.3k
    } else {
502
4.07k
        ++token->_num_unsubmitted_tasks;
503
4.07k
    }
504
24.4k
    _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
24.4k
    if (!_idle_threads.empty()) {
513
18.3k
        _idle_threads.front().not_empty.notify_one();
514
18.3k
        _idle_threads.pop_front();
515
18.3k
    }
516
24.4k
    l.unlock();
517
518
24.4k
    if (need_a_thread) {
519
763
        Status status = create_thread();
520
763
        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
763
    }
533
534
24.4k
    return Status::OK();
535
24.4k
}
536
537
114
void ThreadPool::wait() {
538
114
    std::unique_lock<std::mutex> l(_lock);
539
114
    check_not_pool_thread_unlocked();
540
193
    _idle_cond.wait(l, [this]() { return _total_queued_tasks == 0 && _active_threads == 0; });
541
114
}
542
543
7.75k
void ThreadPool::dispatch_thread() {
544
7.75k
    std::unique_lock<std::mutex> l(_lock);
545
7.75k
    if (!_threads.insert(Thread::current_thread()).second) {
546
0
        throw Exception(Status::InternalError("duplicate token"));
547
0
    }
548
7.75k
    DCHECK_GT(_num_threads_pending_start, 0);
549
7.75k
    _num_threads++;
550
7.75k
    _num_threads_pending_start--;
551
552
7.75k
    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
7.75k
    IdleThread me;
558
559
1.76M
    while (true) {
560
        // Note: Status::Aborted() is used to indicate normal shutdown.
561
1.75M
        if (!_pool_status.ok()) {
562
4.36k
            VLOG_CRITICAL << "DispatchThread exiting: " << _pool_status.to_string();
563
4.36k
            break;
564
4.36k
        }
565
566
1.75M
        if (_num_threads + _num_threads_pending_start > _max_threads) {
567
2
            break;
568
2
        }
569
570
1.75M
        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
1.73M
            _idle_threads.push_front(me);
575
1.73M
            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
1.72M
                if (me.is_linked()) {
580
1.70M
                    _idle_threads.erase(_idle_threads.iterator_to(me));
581
1.70M
                }
582
1.72M
            };
583
1.73M
            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
1.70M
                if (_queue.empty() && _num_threads + _num_threads_pending_start > _min_threads) {
591
611
                    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
611
                    break;
597
611
                }
598
1.70M
            }
599
1.73M
            continue;
600
1.73M
        }
601
602
22.8k
        MonotonicStopWatch task_execution_time_watch;
603
22.8k
        task_execution_time_watch.start();
604
        // Get the next token and task to execute.
605
22.8k
        ThreadPoolToken* token = _queue.front();
606
22.8k
        _queue.pop_front();
607
22.8k
        DCHECK_EQ(ThreadPoolToken::State::RUNNING, token->state());
608
22.8k
        DCHECK(!token->_entries.empty());
609
22.8k
        Task task = std::move(token->_entries.front());
610
22.8k
        thread_pool_task_wait_worker_time_ns_total->increment(
611
22.8k
                task.submit_time_wather.elapsed_time());
612
22.8k
        thread_pool_task_wait_worker_count_total->increment(1);
613
22.8k
        token->_entries.pop_front();
614
22.8k
        token->_active_threads++;
615
22.8k
        --_total_queued_tasks;
616
22.8k
        ++_active_threads;
617
618
22.8k
        l.unlock();
619
620
        // Execute the task
621
22.8k
        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
22.8k
        task.runnable.reset();
629
22.8k
        l.lock();
630
22.8k
        thread_pool_task_execution_time_ns_total->increment(
631
22.8k
                task_execution_time_watch.elapsed_time());
632
22.8k
        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
22.8k
        ThreadPoolToken::State state = token->state();
638
22.8k
        DCHECK(state == ThreadPoolToken::State::RUNNING ||
639
22.8k
               state == ThreadPoolToken::State::QUIESCING);
640
22.8k
        --token->_active_threads;
641
22.8k
        --token->_num_submitted_tasks;
642
643
        // handle shutdown && idle
644
22.8k
        if (token->_active_threads == 0) {
645
13.4k
            if (state == ThreadPoolToken::State::QUIESCING) {
646
852
                DCHECK(token->_entries.empty());
647
852
                token->transition(ThreadPoolToken::State::QUIESCED);
648
12.6k
            } else if (token->_entries.empty()) {
649
9.33k
                token->transition(ThreadPoolToken::State::IDLE);
650
9.33k
            }
651
13.4k
        }
652
653
        // We decrease _num_submitted_tasks holding lock, so the following DCHECK works.
654
22.8k
        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
22.8k
        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
3.15k
            _queue.emplace_back(token);
663
3.15k
            ++token->_num_submitted_tasks;
664
3.15k
            --token->_num_unsubmitted_tasks;
665
3.15k
        }
666
667
22.8k
        if (--_active_threads == 0) {
668
5.37k
            _idle_cond.notify_all();
669
5.37k
        }
670
22.8k
    }
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
7.75k
    CHECK(l.owns_lock());
676
677
7.75k
    CHECK_EQ(_threads.erase(Thread::current_thread()), 1);
678
7.75k
    _num_threads--;
679
7.75k
    if (_num_threads + _num_threads_pending_start == 0) {
680
1.11k
        _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.11k
        CHECK(_queue.empty());
685
1.11k
        DCHECK_EQ(0, _total_queued_tasks);
686
1.11k
    }
687
7.75k
}
688
689
7.75k
Status ThreadPool::create_thread() {
690
7.75k
    return Thread::create("thread pool", absl::Substitute("$0 [worker]", _name),
691
7.75k
                          &ThreadPool::dispatch_thread, this, nullptr);
692
7.75k
}
693
694
10.8k
void ThreadPool::check_not_pool_thread_unlocked() {
695
10.8k
    Thread* current = Thread::current_thread();
696
10.8k
    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
10.8k
}
703
704
34
Status ThreadPool::set_min_threads(int min_threads) {
705
34
    std::lock_guard<std::mutex> l(_lock);
706
34
    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
31
    _min_threads = min_threads;
711
31
    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
31
    return Status::OK();
716
31
}
717
718
38
Status ThreadPool::set_max_threads(int max_threads) {
719
38
    std::lock_guard<std::mutex> l(_lock);
720
38
    DBUG_EXECUTE_IF("ThreadPool.set_max_threads.force_set", {
721
38
        _max_threads = max_threads;
722
38
        return Status::OK();
723
38
    })
724
38
    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
36
    _max_threads = max_threads;
730
36
    if (_max_threads > _num_threads + _num_threads_pending_start) {
731
22
        int addition_threads = _max_threads - _num_threads - _num_threads_pending_start;
732
22
        addition_threads = std::min(addition_threads, _total_queued_tasks);
733
22
        RETURN_IF_ERROR(try_create_thread(addition_threads, l));
734
22
    }
735
36
    return Status::OK();
736
36
}
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