Coverage Report

Created: 2025-12-27 02:54

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