Coverage Report

Created: 2025-11-21 09:41

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
43.1k
    explicit FunctionRunnable(std::function<void()> func) : _func(std::move(func)) {}
59
60
39.5k
    void run() override { _func(); }
61
62
private:
63
    std::function<void()> _func;
64
};
65
66
ThreadPoolBuilder::ThreadPoolBuilder(string name, string workload_group)
67
682
        : _name(std::move(name)),
68
682
          _workload_group(std::move(workload_group)),
69
682
          _min_threads(0),
70
682
          _max_threads(std::thread::hardware_concurrency()),
71
682
          _max_queue_size(std::numeric_limits<int>::max()),
72
682
          _idle_timeout(std::chrono::milliseconds(500)) {}
73
74
634
ThreadPoolBuilder& ThreadPoolBuilder::set_min_threads(int min_threads) {
75
634
    CHECK_GE(min_threads, 0);
76
634
    _min_threads = min_threads;
77
634
    return *this;
78
634
}
79
80
654
ThreadPoolBuilder& ThreadPoolBuilder::set_max_threads(int max_threads) {
81
654
    CHECK_GT(max_threads, 0);
82
654
    _max_threads = max_threads;
83
654
    return *this;
84
654
}
85
86
104
ThreadPoolBuilder& ThreadPoolBuilder::set_max_queue_size(int max_queue_size) {
87
104
    _max_queue_size = max_queue_size;
88
104
    return *this;
89
104
}
90
91
ThreadPoolBuilder& ThreadPoolBuilder::set_cgroup_cpu_ctl(
92
40
        std::weak_ptr<CgroupCpuCtl> cgroup_cpu_ctl) {
93
40
    _cgroup_cpu_ctl = cgroup_cpu_ctl;
94
40
    return *this;
95
40
}
96
97
ThreadPoolToken::ThreadPoolToken(ThreadPool* pool, ThreadPool::ExecutionMode mode,
98
                                 int max_concurrency)
99
5.54k
        : _mode(mode),
100
5.54k
          _pool(pool),
101
5.54k
          _state(State::IDLE),
102
5.54k
          _active_threads(0),
103
5.54k
          _max_concurrency(max_concurrency),
104
5.54k
          _num_submitted_tasks(0),
105
5.54k
          _num_unsubmitted_tasks(0) {
106
5.54k
    if (max_concurrency == 1 && mode != ThreadPool::ExecutionMode::SERIAL) {
107
15
        _mode = ThreadPool::ExecutionMode::SERIAL;
108
15
    }
109
5.54k
}
110
111
5.36k
ThreadPoolToken::~ThreadPoolToken() {
112
5.36k
    shutdown();
113
5.36k
    _pool->release_token(this);
114
5.36k
}
115
116
27.3k
Status ThreadPoolToken::submit(std::shared_ptr<Runnable> r) {
117
27.3k
    return _pool->do_submit(std::move(r), this);
118
27.3k
}
119
120
27.3k
Status ThreadPoolToken::submit_func(std::function<void()> f) {
121
27.3k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
122
27.3k
}
123
124
8.40k
void ThreadPoolToken::shutdown() {
125
8.40k
    std::unique_lock<std::mutex> l(_pool->_lock);
126
8.40k
    _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
8.40k
    std::deque<ThreadPool::Task> to_release = std::move(_entries);
133
8.40k
    _pool->_total_queued_tasks -= to_release.size();
134
135
8.40k
    switch (state()) {
136
4.07k
    case State::IDLE:
137
        // There were no tasks outstanding; we can quiesce the token immediately.
138
4.07k
        transition(State::QUIESCED);
139
4.07k
        break;
140
827
    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
3.76k
        for (auto it = _pool->_queue.begin(); it != _pool->_queue.end();) {
151
2.94k
            if (*it == this) {
152
278
                it = _pool->_queue.erase(it);
153
2.66k
            } else {
154
2.66k
                it++;
155
2.66k
            }
156
2.94k
        }
157
158
827
        if (_active_threads == 0) {
159
132
            transition(State::QUIESCED);
160
132
            break;
161
132
        }
162
695
        transition(State::QUIESCING);
163
695
        [[fallthrough]];
164
712
    case State::QUIESCING:
165
        // The token is already quiescing. Just wait for a worker thread to
166
        // switch it to QUIESCED.
167
1.42k
        _not_running_cond.wait(l, [this]() { return state() == State::QUIESCED; });
168
712
        break;
169
3.49k
    default:
170
3.49k
        break;
171
8.40k
    }
172
8.40k
}
173
174
4.06k
void ThreadPoolToken::wait() {
175
4.06k
    std::unique_lock<std::mutex> l(_pool->_lock);
176
4.06k
    _pool->check_not_pool_thread_unlocked();
177
4.69k
    _not_running_cond.wait(l, [this]() { return !is_active(); });
178
4.06k
}
179
180
51.7k
void ThreadPoolToken::transition(State new_state) {
181
51.7k
#ifndef NDEBUG
182
51.7k
    CHECK_NE(_state, new_state);
183
184
51.7k
    switch (_state) {
185
27.8k
    case State::IDLE:
186
27.8k
        CHECK(new_state == State::RUNNING || new_state == State::QUIESCED);
187
27.8k
        if (new_state == State::RUNNING) {
188
23.2k
            CHECK(!_entries.empty());
189
23.2k
        } else {
190
4.52k
            CHECK(_entries.empty());
191
4.52k
            CHECK_EQ(_active_threads, 0);
192
4.52k
        }
193
27.8k
        break;
194
23.2k
    case State::RUNNING:
195
23.2k
        CHECK(new_state == State::IDLE || new_state == State::QUIESCING ||
196
23.2k
              new_state == State::QUIESCED);
197
23.2k
        CHECK(_entries.empty());
198
23.2k
        if (new_state == State::QUIESCING) {
199
715
            CHECK_GT(_active_threads, 0);
200
715
        }
201
23.2k
        break;
202
715
    case State::QUIESCING:
203
715
        CHECK(new_state == State::QUIESCED);
204
715
        CHECK_EQ(_active_threads, 0);
205
715
        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
51.7k
    }
212
51.7k
#endif
213
214
    // Take actions based on the state we're entering.
215
51.7k
    switch (new_state) {
216
22.4k
    case State::IDLE:
217
27.7k
    case State::QUIESCED:
218
27.7k
        _not_running_cond.notify_all();
219
27.7k
        break;
220
23.9k
    default:
221
23.9k
        break;
222
51.7k
    }
223
224
51.7k
    _state = new_state;
225
51.7k
}
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
40.9k
bool ThreadPoolToken::need_dispatch() {
246
40.9k
    return _state == ThreadPoolToken::State::IDLE ||
247
40.9k
           (_mode == ThreadPool::ExecutionMode::CONCURRENT &&
248
17.6k
            _num_submitted_tasks < _max_concurrency);
249
40.9k
}
250
251
ThreadPool::ThreadPool(const ThreadPoolBuilder& builder)
252
641
        : _name(builder._name),
253
641
          _workload_group(builder._workload_group),
254
641
          _min_threads(builder._min_threads),
255
641
          _max_threads(builder._max_threads),
256
641
          _max_queue_size(builder._max_queue_size),
257
641
          _idle_timeout(builder._idle_timeout),
258
641
          _pool_status(Status::Uninitialized("The pool was not initialized.")),
259
641
          _num_threads(0),
260
641
          _num_threads_pending_start(0),
261
641
          _active_threads(0),
262
641
          _total_queued_tasks(0),
263
641
          _cgroup_cpu_ctl(builder._cgroup_cpu_ctl),
264
641
          _tokenless(new_token(ExecutionMode::CONCURRENT)),
265
641
          _id(UniqueId::gen_uid()) {}
266
267
468
ThreadPool::~ThreadPool() {
268
    // There should only be one live token: the one used in tokenless submission.
269
468
    CHECK_EQ(1, _tokens.size()) << absl::Substitute(
270
0
            "Threadpool $0 destroyed with $1 allocated tokens", _name, _tokens.size());
271
468
    shutdown();
272
468
    VLOG_DEBUG << fmt::format("Thread pool {} destroyed", _name);
273
468
}
274
275
646
Status ThreadPool::try_create_thread(int thread_num, std::lock_guard<std::mutex>&) {
276
6.33k
    for (int i = 0; i < thread_num; i++) {
277
5.68k
        Status status = create_thread();
278
5.68k
        if (status.ok()) {
279
5.68k
            _num_threads_pending_start++;
280
5.68k
        } else {
281
0
            LOG(WARNING) << "Thread pool " << _name << " failed to create thread: " << status;
282
0
            return status;
283
0
        }
284
5.68k
    }
285
646
    return Status::OK();
286
646
}
287
288
641
Status ThreadPool::init() {
289
641
    if (!_pool_status.is<UNINITIALIZED>()) {
290
0
        return Status::NotSupported("The thread pool {} is already initialized", _name);
291
0
    }
292
641
    _pool_status = Status::OK();
293
294
641
    {
295
641
        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
641
        static_cast<void>(try_create_thread(_min_threads, l));
299
641
    }
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
641
    _metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
305
641
            fmt::format("thread_pool_{}", _name), {{"thread_pool_name", _name},
306
641
                                                   {"workload_group", _workload_group},
307
641
                                                   {"id", _id.to_string()}});
308
309
641
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_active_threads);
310
641
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_threads);
311
641
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_queue_size);
312
641
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_queue_size);
313
641
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_time_ns_total);
314
641
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_count_total);
315
641
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_time_ns_total);
316
641
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_count_total);
317
641
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_submit_failed);
318
319
7.17k
    _metric_entity->register_hook("update", [this]() {
320
7.17k
        {
321
7.17k
            std::lock_guard<std::mutex> l(_lock);
322
7.17k
            if (!_pool_status.ok()) {
323
0
                return;
324
0
            }
325
7.17k
        }
326
327
7.17k
        thread_pool_active_threads->set_value(num_active_threads());
328
7.17k
        thread_pool_queue_size->set_value(get_queue_size());
329
7.17k
        thread_pool_max_queue_size->set_value(get_max_queue_size());
330
7.17k
        thread_pool_max_threads->set_value(max_threads());
331
7.17k
    });
332
641
    return Status::OK();
333
641
}
334
335
838
void ThreadPool::shutdown() {
336
838
    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
838
    DorisMetrics::instance()->metric_registry()->deregister_entity(_metric_entity);
342
838
    std::unique_lock<std::mutex> l(_lock);
343
838
    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
838
    _pool_status = Status::Error<SERVICE_UNAVAILABLE, false>(
351
838
            "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
838
    _queue.clear();
358
359
838
    std::deque<std::deque<Task>> to_release;
360
840
    for (auto* t : _tokens) {
361
840
        if (!t->_entries.empty()) {
362
3
            to_release.emplace_back(std::move(t->_entries));
363
3
        }
364
840
        switch (t->state()) {
365
450
        case ThreadPoolToken::State::IDLE:
366
            // The token is idle; we can quiesce it immediately.
367
450
            t->transition(ThreadPoolToken::State::QUIESCED);
368
450
            break;
369
20
        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
20
            t->transition(t->_active_threads > 0 ? ThreadPoolToken::State::QUIESCING
375
20
                                                 : ThreadPoolToken::State::QUIESCED);
376
20
            break;
377
370
        default:
378
370
            break;
379
840
        }
380
840
    }
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
838
    _total_queued_tasks = 0;
386
3.94k
    while (!_idle_threads.empty()) {
387
3.10k
        _idle_threads.front().not_empty.notify_one();
388
3.10k
        _idle_threads.pop_front();
389
3.10k
    }
390
391
1.27k
    _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
840
    for (auto* t : _tokens) {
395
840
        DCHECK(t->state() == ThreadPoolToken::State::IDLE ||
396
840
               t->state() == ThreadPoolToken::State::QUIESCED);
397
840
    }
398
838
}
399
400
5.54k
std::unique_ptr<ThreadPoolToken> ThreadPool::new_token(ExecutionMode mode, int max_concurrency) {
401
5.54k
    std::lock_guard<std::mutex> l(_lock);
402
5.54k
    std::unique_ptr<ThreadPoolToken> t(new ThreadPoolToken(this, mode, max_concurrency));
403
5.54k
    if (!_tokens.insert(t.get()).second) {
404
0
        throw Exception(Status::InternalError("duplicate token"));
405
0
    }
406
5.54k
    return t;
407
5.54k
}
408
409
5.36k
void ThreadPool::release_token(ThreadPoolToken* t) {
410
5.36k
    std::lock_guard<std::mutex> l(_lock);
411
5.36k
    CHECK(!t->is_active()) << absl::Substitute("Token with state $0 may not be released",
412
0
                                               ThreadPoolToken::state_to_string(t->state()));
413
5.36k
    CHECK_EQ(1, _tokens.erase(t));
414
5.36k
}
415
416
16.3k
Status ThreadPool::submit(std::shared_ptr<Runnable> r) {
417
16.3k
    return do_submit(std::move(r), _tokenless.get());
418
16.3k
}
419
420
15.7k
Status ThreadPool::submit_func(std::function<void()> f) {
421
15.7k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
422
15.7k
}
423
424
43.7k
Status ThreadPool::do_submit(std::shared_ptr<Runnable> r, ThreadPoolToken* token) {
425
43.7k
    DCHECK(token);
426
427
43.7k
    std::unique_lock<std::mutex> l(_lock);
428
43.7k
    if (!_pool_status.ok()) [[unlikely]] {
429
1
        return _pool_status;
430
1
    }
431
432
43.7k
    if (!token->may_submit_new_tasks()) [[unlikely]] {
433
2.82k
        return Status::Error<SERVICE_UNAVAILABLE>("Thread pool({}) token was shut down", _name);
434
2.82k
    }
435
436
    // Size limit check.
437
40.9k
    int64_t capacity_remaining = static_cast<int64_t>(_max_threads) - _active_threads +
438
40.9k
                                 static_cast<int64_t>(_max_queue_size) - _total_queued_tasks;
439
40.9k
    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
40.8k
    int threads_from_this_submit =
464
40.8k
            token->is_active() && token->mode() == ExecutionMode::SERIAL ? 0 : 1;
465
40.8k
    int inactive_threads = _num_threads + _num_threads_pending_start - _active_threads;
466
40.8k
    int additional_threads =
467
40.8k
            static_cast<int>(_queue.size()) + threads_from_this_submit - inactive_threads;
468
40.8k
    bool need_a_thread = false;
469
40.8k
    if (additional_threads > 0 && _num_threads + _num_threads_pending_start < _max_threads) {
470
775
        need_a_thread = true;
471
775
        _num_threads_pending_start++;
472
775
    }
473
474
40.8k
    Task task;
475
40.8k
    task.runnable = std::move(r);
476
40.8k
    task.submit_time_wather.start();
477
478
    // Add the task to the token's queue.
479
40.8k
    ThreadPoolToken::State state = token->state();
480
40.8k
    DCHECK(state == ThreadPoolToken::State::IDLE || state == ThreadPoolToken::State::RUNNING);
481
40.8k
    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
40.8k
    if (token->need_dispatch()) {
491
39.0k
        _queue.emplace_back(token);
492
39.0k
        ++token->_num_submitted_tasks;
493
39.0k
        if (state == ThreadPoolToken::State::IDLE) {
494
23.2k
            token->transition(ThreadPoolToken::State::RUNNING);
495
23.2k
        }
496
39.0k
    } else {
497
1.89k
        ++token->_num_unsubmitted_tasks;
498
1.89k
    }
499
40.8k
    _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
40.8k
    if (!_idle_threads.empty()) {
508
30.7k
        _idle_threads.front().not_empty.notify_one();
509
30.7k
        _idle_threads.pop_front();
510
30.7k
    }
511
40.8k
    l.unlock();
512
513
40.8k
    if (need_a_thread) {
514
775
        Status status = create_thread();
515
775
        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
775
    }
528
529
40.8k
    return Status::OK();
530
40.8k
}
531
532
99
void ThreadPool::wait() {
533
99
    std::unique_lock<std::mutex> l(_lock);
534
99
    check_not_pool_thread_unlocked();
535
171
    _idle_cond.wait(l, [this]() { return _total_queued_tasks == 0 && _active_threads == 0; });
536
99
}
537
538
6.46k
void ThreadPool::dispatch_thread() {
539
6.46k
    std::unique_lock<std::mutex> l(_lock);
540
6.46k
    if (!_threads.insert(Thread::current_thread()).second) {
541
0
        throw Exception(Status::InternalError("duplicate token"));
542
0
    }
543
6.46k
    DCHECK_GT(_num_threads_pending_start, 0);
544
6.46k
    _num_threads++;
545
6.46k
    _num_threads_pending_start--;
546
547
6.46k
    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
6.46k
    IdleThread me;
553
554
2.10M
    while (true) {
555
        // Note: Status::Aborted() is used to indicate normal shutdown.
556
2.10M
        if (!_pool_status.ok()) {
557
3.44k
            VLOG_CRITICAL << "DispatchThread exiting: " << _pool_status.to_string();
558
3.44k
            break;
559
3.44k
        }
560
561
2.10M
        if (_num_threads + _num_threads_pending_start > _max_threads) {
562
2
            break;
563
2
        }
564
565
2.10M
        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.06M
            _idle_threads.push_front(me);
570
2.06M
            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.05M
                if (me.is_linked()) {
575
2.02M
                    _idle_threads.erase(_idle_threads.iterator_to(me));
576
2.02M
                }
577
2.05M
            };
578
2.06M
            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.02M
                if (_queue.empty() && _num_threads + _num_threads_pending_start > _min_threads) {
586
632
                    VLOG_NOTICE << "Releasing worker thread from pool " << _name << " after "
587
505
                                << std::chrono::duration_cast<std::chrono::milliseconds>(
588
505
                                           _idle_timeout)
589
505
                                           .count()
590
505
                                << "ms of idle time.";
591
632
                    break;
592
632
                }
593
2.02M
            }
594
2.06M
            continue;
595
2.06M
        }
596
597
39.5k
        MonotonicStopWatch task_execution_time_watch;
598
39.5k
        task_execution_time_watch.start();
599
        // Get the next token and task to execute.
600
39.5k
        ThreadPoolToken* token = _queue.front();
601
39.5k
        _queue.pop_front();
602
39.5k
        DCHECK_EQ(ThreadPoolToken::State::RUNNING, token->state());
603
39.5k
        DCHECK(!token->_entries.empty());
604
39.5k
        Task task = std::move(token->_entries.front());
605
39.5k
        thread_pool_task_wait_worker_time_ns_total->increment(
606
39.5k
                task.submit_time_wather.elapsed_time());
607
39.5k
        thread_pool_task_wait_worker_count_total->increment(1);
608
39.5k
        token->_entries.pop_front();
609
39.5k
        token->_active_threads++;
610
39.5k
        --_total_queued_tasks;
611
39.5k
        ++_active_threads;
612
613
39.5k
        l.unlock();
614
615
        // Execute the task
616
39.5k
        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
39.5k
        task.runnable.reset();
624
39.5k
        l.lock();
625
39.5k
        thread_pool_task_execution_time_ns_total->increment(
626
39.5k
                task_execution_time_watch.elapsed_time());
627
39.5k
        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
39.5k
        ThreadPoolToken::State state = token->state();
633
39.5k
        DCHECK(state == ThreadPoolToken::State::RUNNING ||
634
39.5k
               state == ThreadPoolToken::State::QUIESCING);
635
39.5k
        --token->_active_threads;
636
39.5k
        --token->_num_submitted_tasks;
637
638
        // handle shutdown && idle
639
39.5k
        if (token->_active_threads == 0) {
640
24.6k
            if (state == ThreadPoolToken::State::QUIESCING) {
641
715
                DCHECK(token->_entries.empty());
642
715
                token->transition(ThreadPoolToken::State::QUIESCED);
643
23.8k
            } else if (token->_entries.empty()) {
644
22.4k
                token->transition(ThreadPoolToken::State::IDLE);
645
22.4k
            }
646
24.6k
        }
647
648
        // We decrease _num_submitted_tasks holding lock, so the following DCHECK works.
649
39.5k
        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
39.5k
        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.39k
            _queue.emplace_back(token);
658
1.39k
            ++token->_num_submitted_tasks;
659
1.39k
            --token->_num_unsubmitted_tasks;
660
1.39k
        }
661
662
39.5k
        if (--_active_threads == 0) {
663
16.4k
            _idle_cond.notify_all();
664
16.4k
        }
665
39.5k
    }
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
6.46k
    CHECK(l.owns_lock());
671
672
6.46k
    CHECK_EQ(_threads.erase(Thread::current_thread()), 1);
673
6.46k
    _num_threads--;
674
6.46k
    if (_num_threads + _num_threads_pending_start == 0) {
675
941
        _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
941
        CHECK(_queue.empty());
680
941
        DCHECK_EQ(0, _total_queued_tasks);
681
941
    }
682
6.46k
}
683
684
6.46k
Status ThreadPool::create_thread() {
685
6.46k
    return Thread::create("thread pool", absl::Substitute("$0 [worker]", _name),
686
6.46k
                          &ThreadPool::dispatch_thread, this, nullptr);
687
6.46k
}
688
689
13.4k
void ThreadPool::check_not_pool_thread_unlocked() {
690
13.4k
    Thread* current = Thread::current_thread();
691
13.4k
    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
13.4k
}
698
699
4
Status ThreadPool::set_min_threads(int min_threads) {
700
4
    std::lock_guard<std::mutex> l(_lock);
701
4
    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
3
    _min_threads = min_threads;
706
3
    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
3
    return Status::OK();
711
3
}
712
713
8
Status ThreadPool::set_max_threads(int max_threads) {
714
8
    std::lock_guard<std::mutex> l(_lock);
715
8
    DBUG_EXECUTE_IF("ThreadPool.set_max_threads.force_set", {
716
8
        _max_threads = max_threads;
717
8
        return Status::OK();
718
8
    })
719
8
    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
7
    _max_threads = max_threads;
725
7
    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
7
    return Status::OK();
731
7
}
732
733
0
std::ostream& operator<<(std::ostream& o, ThreadPoolToken::State s) {
734
0
    return o << ThreadPoolToken::state_to_string(s);
735
0
}
736
737
} // namespace doris