Coverage Report

Created: 2025-11-17 11:36

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