Coverage Report

Created: 2025-09-15 20:29

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