Coverage Report

Created: 2025-03-13 18:46

/root/doris/be/src/util/threadpool.cpp
Line
Count
Source (jump to first uncovered line)
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 "common/exception.h"
31
#include "common/logging.h"
32
#include "gutil/map-util.h"
33
#include "gutil/port.h"
34
#include "gutil/strings/substitute.h"
35
#include "util/debug/sanitizer_scopes.h"
36
#include "util/doris_metrics.h"
37
#include "util/metrics.h"
38
#include "util/scoped_cleanup.h"
39
#include "util/stopwatch.hpp"
40
#include "util/thread.h"
41
42
namespace doris {
43
// The name of these varialbs will be useds as metric name in prometheus.
44
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_active_threads, MetricUnit::NOUNIT);
45
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_queue_size, MetricUnit::NOUNIT);
46
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_max_queue_size, MetricUnit::NOUNIT);
47
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(thread_pool_max_threads, MetricUnit::NOUNIT);
48
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_submit_failed, MetricUnit::NOUNIT);
49
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_execution_time_ns_total,
50
                                     MetricUnit::NANOSECONDS);
51
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_execution_count_total, MetricUnit::NOUNIT);
52
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_wait_worker_time_ns_total,
53
                                     MetricUnit::NANOSECONDS);
54
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(thread_pool_task_wait_worker_count_total, MetricUnit::NOUNIT);
55
using namespace ErrorCode;
56
57
using std::string;
58
using strings::Substitute;
59
60
class FunctionRunnable : public Runnable {
61
public:
62
7.57k
    explicit FunctionRunnable(std::function<void()> func) : _func(std::move(func)) {}
63
64
4.35k
    void run() override { _func(); }
65
66
private:
67
    std::function<void()> _func;
68
};
69
70
ThreadPoolBuilder::ThreadPoolBuilder(string name, string workload_group)
71
        : _name(std::move(name)),
72
          _workload_group(std::move(workload_group)),
73
          _min_threads(0),
74
          _max_threads(std::thread::hardware_concurrency()),
75
          _max_queue_size(std::numeric_limits<int>::max()),
76
289
          _idle_timeout(std::chrono::milliseconds(500)) {}
77
78
253
ThreadPoolBuilder& ThreadPoolBuilder::set_min_threads(int min_threads) {
79
253
    CHECK_GE(min_threads, 0);
80
253
    _min_threads = min_threads;
81
253
    return *this;
82
253
}
83
84
261
ThreadPoolBuilder& ThreadPoolBuilder::set_max_threads(int max_threads) {
85
261
    CHECK_GT(max_threads, 0);
86
261
    _max_threads = max_threads;
87
261
    return *this;
88
261
}
89
90
62
ThreadPoolBuilder& ThreadPoolBuilder::set_max_queue_size(int max_queue_size) {
91
62
    _max_queue_size = max_queue_size;
92
62
    return *this;
93
62
}
94
95
ThreadPoolBuilder& ThreadPoolBuilder::set_cgroup_cpu_ctl(
96
0
        std::weak_ptr<CgroupCpuCtl> cgroup_cpu_ctl) {
97
0
    _cgroup_cpu_ctl = cgroup_cpu_ctl;
98
0
    return *this;
99
0
}
100
101
ThreadPoolToken::ThreadPoolToken(ThreadPool* pool, ThreadPool::ExecutionMode mode,
102
                                 int max_concurrency)
103
        : _mode(mode),
104
          _pool(pool),
105
          _state(State::IDLE),
106
          _active_threads(0),
107
          _max_concurrency(max_concurrency),
108
          _num_submitted_tasks(0),
109
2.11k
          _num_unsubmitted_tasks(0) {
110
2.11k
    if (max_concurrency == 1 && mode != ThreadPool::ExecutionMode::SERIAL) {
111
1
        _mode = ThreadPool::ExecutionMode::SERIAL;
112
1
    }
113
2.11k
}
114
115
2.10k
ThreadPoolToken::~ThreadPoolToken() {
116
2.10k
    shutdown();
117
2.10k
    _pool->release_token(this);
118
2.10k
}
119
120
6.20k
Status ThreadPoolToken::submit(std::shared_ptr<Runnable> r) {
121
6.20k
    return _pool->do_submit(std::move(r), this);
122
6.20k
}
123
124
6.49k
Status ThreadPoolToken::submit_func(std::function<void()> f) {
125
6.49k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
126
6.49k
}
127
128
3.29k
void ThreadPoolToken::shutdown() {
129
3.29k
    std::unique_lock<std::mutex> l(_pool->_lock);
130
3.29k
    _pool->check_not_pool_thread_unlocked();
131
132
    // Clear the queue under the lock, but defer the releasing of the tasks
133
    // outside the lock, in case there are concurrent threads wanting to access
134
    // the ThreadPool. The task's destructors may acquire locks, etc, so this
135
    // also prevents lock inversions.
136
3.29k
    std::deque<ThreadPool::Task> to_release = std::move(_entries);
137
3.29k
    _pool->_total_queued_tasks -= to_release.size();
138
139
3.29k
    switch (state()) {
140
927
    case State::IDLE:
141
        // There were no tasks outstanding; we can quiesce the token immediately.
142
927
        transition(State::QUIESCED);
143
927
        break;
144
855
    case State::RUNNING:
145
        // There were outstanding tasks. If any are still running, switch to
146
        // QUIESCING and wait for them to finish (the worker thread executing
147
        // the token's last task will switch the token to QUIESCED). Otherwise,
148
        // we can quiesce the token immediately.
149
150
        // Note: this is an O(n) operation, but it's expected to be infrequent.
151
        // Plus doing it this way (rather than switching to QUIESCING and waiting
152
        // for a worker thread to process the queue entry) helps retain state
153
        // transition symmetry with ThreadPool::shutdown.
154
5.86k
        for (auto it = _pool->_queue.begin(); it != _pool->_queue.end();) {
155
5.01k
            if (*it == this) {
156
532
                it = _pool->_queue.erase(it);
157
4.48k
            } else {
158
4.48k
                it++;
159
4.48k
            }
160
5.01k
        }
161
162
855
        if (_active_threads == 0) {
163
298
            transition(State::QUIESCED);
164
298
            break;
165
298
        }
166
557
        transition(State::QUIESCING);
167
557
        [[fallthrough]];
168
570
    case State::QUIESCING:
169
        // The token is already quiescing. Just wait for a worker thread to
170
        // switch it to QUIESCED.
171
1.14k
        _not_running_cond.wait(l, [this]() { return state() == State::QUIESCED; });
172
570
        break;
173
1.49k
    default:
174
1.49k
        break;
175
3.29k
    }
176
3.29k
}
177
178
838
void ThreadPoolToken::wait() {
179
838
    std::unique_lock<std::mutex> l(_pool->_lock);
180
838
    _pool->check_not_pool_thread_unlocked();
181
1.05k
    _not_running_cond.wait(l, [this]() { return !is_active(); });
182
838
}
183
184
7.09k
void ThreadPoolToken::transition(State new_state) {
185
7.09k
#ifndef NDEBUG
186
7.09k
    CHECK_NE(_state, new_state);
187
188
7.09k
    switch (_state) {
189
3.88k
    case State::IDLE:
190
3.88k
        CHECK(new_state == State::RUNNING || new_state == State::QUIESCED);
191
3.88k
        if (new_state == State::RUNNING) {
192
2.64k
            CHECK(!_entries.empty());
193
2.64k
        } else {
194
1.23k
            CHECK(_entries.empty());
195
1.23k
            CHECK_EQ(_active_threads, 0);
196
1.23k
        }
197
3.88k
        break;
198
2.64k
    case State::RUNNING:
199
2.64k
        CHECK(new_state == State::IDLE || new_state == State::QUIESCING ||
200
2.64k
              new_state == State::QUIESCED);
201
2.64k
        CHECK(_entries.empty());
202
2.64k
        if (new_state == State::QUIESCING) {
203
567
            CHECK_GT(_active_threads, 0);
204
567
        }
205
2.64k
        break;
206
567
    case State::QUIESCING:
207
567
        CHECK(new_state == State::QUIESCED);
208
567
        CHECK_EQ(_active_threads, 0);
209
567
        break;
210
0
    case State::QUIESCED:
211
0
        CHECK(false); // QUIESCED is a terminal state
212
0
        break;
213
0
    default:
214
0
        throw Exception(Status::FatalError("Unknown token state: {}", _state));
215
7.09k
    }
216
7.09k
#endif
217
218
    // Take actions based on the state we're entering.
219
7.09k
    switch (new_state) {
220
1.77k
    case State::IDLE:
221
3.88k
    case State::QUIESCED:
222
3.88k
        _not_running_cond.notify_all();
223
3.88k
        break;
224
3.21k
    default:
225
3.21k
        break;
226
7.09k
    }
227
228
7.09k
    _state = new_state;
229
7.09k
}
230
231
0
const char* ThreadPoolToken::state_to_string(State s) {
232
0
    switch (s) {
233
0
    case State::IDLE:
234
0
        return "IDLE";
235
0
        break;
236
0
    case State::RUNNING:
237
0
        return "RUNNING";
238
0
        break;
239
0
    case State::QUIESCING:
240
0
        return "QUIESCING";
241
0
        break;
242
0
    case State::QUIESCED:
243
0
        return "QUIESCED";
244
0
        break;
245
0
    }
246
0
    return "<cannot reach here>";
247
0
}
248
249
5.60k
bool ThreadPoolToken::need_dispatch() {
250
5.60k
    return _state == ThreadPoolToken::State::IDLE ||
251
5.60k
           (_mode == ThreadPool::ExecutionMode::CONCURRENT &&
252
2.95k
            _num_submitted_tasks < _max_concurrency);
253
5.60k
}
254
255
ThreadPool::ThreadPool(const ThreadPoolBuilder& builder)
256
        : _name(builder._name),
257
          _workload_group(builder._workload_group),
258
          _min_threads(builder._min_threads),
259
          _max_threads(builder._max_threads),
260
          _max_queue_size(builder._max_queue_size),
261
          _idle_timeout(builder._idle_timeout),
262
          _pool_status(Status::Uninitialized("The pool was not initialized.")),
263
          _num_threads(0),
264
          _num_threads_pending_start(0),
265
          _active_threads(0),
266
          _total_queued_tasks(0),
267
          _cgroup_cpu_ctl(builder._cgroup_cpu_ctl),
268
          _tokenless(new_token(ExecutionMode::CONCURRENT)),
269
284
          _id(UniqueId::gen_uid()) {}
270
271
272
ThreadPool::~ThreadPool() {
272
    // There should only be one live token: the one used in tokenless submission.
273
272
    CHECK_EQ(1, _tokens.size()) << strings::Substitute(
274
0
            "Threadpool $0 destroyed with $1 allocated tokens", _name, _tokens.size());
275
272
    shutdown();
276
272
}
277
278
288
Status ThreadPool::try_create_thread(int thread_num, std::lock_guard<std::mutex>&) {
279
1.15k
    for (int i = 0; i < thread_num; i++) {
280
870
        Status status = create_thread();
281
870
        if (status.ok()) {
282
870
            _num_threads_pending_start++;
283
870
        } else {
284
0
            LOG(WARNING) << "Thread pool " << _name << " failed to create thread: " << status;
285
0
            return status;
286
0
        }
287
870
    }
288
288
    return Status::OK();
289
288
}
290
291
284
Status ThreadPool::init() {
292
284
    if (!_pool_status.is<UNINITIALIZED>()) {
293
0
        return Status::NotSupported("The thread pool {} is already initialized", _name);
294
0
    }
295
284
    _pool_status = Status::OK();
296
297
284
    {
298
284
        std::lock_guard<std::mutex> l(_lock);
299
        // create thread failed should not cause threadpool init failed,
300
        // because thread can be created later such as when submit a task.
301
284
        static_cast<void>(try_create_thread(_min_threads, l));
302
284
    }
303
304
    // _id of thread pool is used to make sure when we create thread pool with same name, we can
305
    // get different _metric_entity
306
    // If not, we will have problem when we deregister entity and register hook.
307
284
    _metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
308
284
            fmt::format("thread_pool_{}", _name), {{"thread_pool_name", _name},
309
284
                                                   {"workload_group", _workload_group},
310
284
                                                   {"id", _id.to_string()}});
311
312
284
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_active_threads);
313
284
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_threads);
314
284
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_queue_size);
315
284
    INT_GAUGE_METRIC_REGISTER(_metric_entity, thread_pool_max_queue_size);
316
284
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_time_ns_total);
317
284
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_execution_count_total);
318
284
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_time_ns_total);
319
284
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_task_wait_worker_count_total);
320
284
    INT_COUNTER_METRIC_REGISTER(_metric_entity, thread_pool_submit_failed);
321
322
284
    _metric_entity->register_hook("update", [this]() {
323
0
        {
324
0
            std::lock_guard<std::mutex> l(_lock);
325
0
            if (!_pool_status.ok()) {
326
0
                return;
327
0
            }
328
0
        }
329
330
0
        thread_pool_active_threads->set_value(num_active_threads());
331
0
        thread_pool_queue_size->set_value(get_queue_size());
332
0
        thread_pool_max_queue_size->set_value(get_max_queue_size());
333
0
        thread_pool_max_threads->set_value(max_threads());
334
0
    });
335
284
    return Status::OK();
336
284
}
337
338
424
void ThreadPool::shutdown() {
339
    // Why access to doris_metrics is safe here?
340
    // Since DorisMetrics is a singleton, it will be destroyed only after doris_main is exited.
341
    // The shutdown/destroy of ThreadPool is guaranteed to take place before doris_main exits by
342
    // ExecEnv::destroy().
343
424
    DorisMetrics::instance()->metric_registry()->deregister_entity(_metric_entity);
344
424
    debug::ScopedTSANIgnoreReadsAndWrites ignore_tsan;
345
424
    std::unique_lock<std::mutex> l(_lock);
346
424
    check_not_pool_thread_unlocked();
347
348
    // Note: this is the same error seen at submission if the pool is at
349
    // capacity, so clients can't tell them apart. This isn't really a practical
350
    // concern though because shutting down a pool typically requires clients to
351
    // be quiesced first, so there's no danger of a client getting confused.
352
    // Not print stack trace here
353
424
    _pool_status = Status::Error<SERVICE_UNAVAILABLE, false>(
354
424
            "The thread pool {} has been shut down.", _name);
355
356
    // Clear the various queues under the lock, but defer the releasing
357
    // of the tasks outside the lock, in case there are concurrent threads
358
    // wanting to access the ThreadPool. The task's destructors may acquire
359
    // locks, etc, so this also prevents lock inversions.
360
424
    _queue.clear();
361
362
424
    std::deque<std::deque<Task>> to_release;
363
499
    for (auto* t : _tokens) {
364
499
        if (!t->_entries.empty()) {
365
7
            to_release.emplace_back(std::move(t->_entries));
366
7
        }
367
499
        switch (t->state()) {
368
311
        case ThreadPoolToken::State::IDLE:
369
            // The token is idle; we can quiesce it immediately.
370
311
            t->transition(ThreadPoolToken::State::QUIESCED);
371
311
            break;
372
14
        case ThreadPoolToken::State::RUNNING:
373
            // The token has tasks associated with it. If they're merely queued
374
            // (i.e. there are no active threads), the tasks will have been removed
375
            // above and we can quiesce immediately. Otherwise, we need to wait for
376
            // the threads to finish.
377
14
            t->transition(t->_active_threads > 0 ? ThreadPoolToken::State::QUIESCING
378
14
                                                 : ThreadPoolToken::State::QUIESCED);
379
14
            break;
380
174
        default:
381
174
            break;
382
499
        }
383
499
    }
384
385
    // The queues are empty. Wake any sleeping worker threads and wait for all
386
    // of them to exit. Some worker threads will exit immediately upon waking,
387
    // while others will exit after they finish executing an outstanding task.
388
424
    _total_queued_tasks = 0;
389
1.33k
    while (!_idle_threads.empty()) {
390
909
        _idle_threads.front().not_empty.notify_one();
391
909
        _idle_threads.pop_front();
392
909
    }
393
394
674
    _no_threads_cond.wait(l, [this]() { return _num_threads + _num_threads_pending_start == 0; });
395
396
    // All the threads have exited. Check the state of each token.
397
499
    for (auto* t : _tokens) {
398
499
        DCHECK(t->state() == ThreadPoolToken::State::IDLE ||
399
499
               t->state() == ThreadPoolToken::State::QUIESCED);
400
499
    }
401
424
}
402
403
2.11k
std::unique_ptr<ThreadPoolToken> ThreadPool::new_token(ExecutionMode mode, int max_concurrency) {
404
2.11k
    std::lock_guard<std::mutex> l(_lock);
405
2.11k
    std::unique_ptr<ThreadPoolToken> t(new ThreadPoolToken(this, mode, max_concurrency));
406
2.11k
    InsertOrDie(&_tokens, t.get());
407
2.11k
    return t;
408
2.11k
}
409
410
2.10k
void ThreadPool::release_token(ThreadPoolToken* t) {
411
2.10k
    std::lock_guard<std::mutex> l(_lock);
412
2.10k
    CHECK(!t->is_active()) << strings::Substitute("Token with state $0 may not be released",
413
0
                                                  ThreadPoolToken::state_to_string(t->state()));
414
2.10k
    CHECK_EQ(1, _tokens.erase(t));
415
2.10k
}
416
417
1.51k
Status ThreadPool::submit(std::shared_ptr<Runnable> r) {
418
1.51k
    return do_submit(std::move(r), _tokenless.get());
419
1.51k
}
420
421
1.33k
Status ThreadPool::submit_func(std::function<void()> f) {
422
1.33k
    return submit(std::make_shared<FunctionRunnable>(std::move(f)));
423
1.33k
}
424
425
7.96k
Status ThreadPool::do_submit(std::shared_ptr<Runnable> r, ThreadPoolToken* token) {
426
7.96k
    DCHECK(token);
427
428
7.96k
    std::unique_lock<std::mutex> l(_lock);
429
7.96k
    if (PREDICT_FALSE(!_pool_status.ok())) {
430
1
        return _pool_status;
431
1
    }
432
433
7.95k
    if (PREDICT_FALSE(!token->may_submit_new_tasks())) {
434
2.44k
        return Status::Error<SERVICE_UNAVAILABLE>("Thread pool({}) token was shut down", _name);
435
2.44k
    }
436
437
    // Size limit check.
438
5.51k
    int64_t capacity_remaining = static_cast<int64_t>(_max_threads) - _active_threads +
439
5.51k
                                 static_cast<int64_t>(_max_queue_size) - _total_queued_tasks;
440
5.51k
    if (capacity_remaining < 1) {
441
4
        thread_pool_submit_failed->increment(1);
442
4
        return Status::Error<SERVICE_UNAVAILABLE>(
443
4
                "Thread pool {} is at capacity ({}/{} tasks running, {}/{} tasks queued)", _name,
444
4
                _num_threads + _num_threads_pending_start, _max_threads, _total_queued_tasks,
445
4
                _max_queue_size);
446
4
    }
447
448
    // Should we create another thread?
449
450
    // We assume that each current inactive thread will grab one item from the
451
    // queue.  If it seems like we'll need another thread, we create one.
452
    //
453
    // Rather than creating the thread here, while holding the lock, we defer
454
    // it to down below. This is because thread creation can be rather slow
455
    // (hundreds of milliseconds in some cases) and we'd like to allow the
456
    // existing threads to continue to process tasks while we do so.
457
    //
458
    // In theory, a currently active thread could finish immediately after this
459
    // calculation but before our new worker starts running. This would mean we
460
    // created a thread we didn't really need. However, this race is unavoidable
461
    // and harmless.
462
    //
463
    // Of course, we never create more than _max_threads threads no matter what.
464
5.51k
    int threads_from_this_submit =
465
5.51k
            token->is_active() && token->mode() == ExecutionMode::SERIAL ? 0 : 1;
466
5.51k
    int inactive_threads = _num_threads + _num_threads_pending_start - _active_threads;
467
5.51k
    int additional_threads =
468
5.51k
            static_cast<int>(_queue.size()) + threads_from_this_submit - inactive_threads;
469
5.51k
    bool need_a_thread = false;
470
5.51k
    if (additional_threads > 0 && _num_threads + _num_threads_pending_start < _max_threads) {
471
624
        need_a_thread = true;
472
624
        _num_threads_pending_start++;
473
624
    }
474
475
5.51k
    Task task;
476
5.51k
    task.runnable = std::move(r);
477
5.51k
    task.submit_time_wather.start();
478
479
    // Add the task to the token's queue.
480
5.51k
    ThreadPoolToken::State state = token->state();
481
5.51k
    DCHECK(state == ThreadPoolToken::State::IDLE || state == ThreadPoolToken::State::RUNNING);
482
5.51k
    token->_entries.emplace_back(std::move(task));
483
    // When we need to execute the task in the token, we submit the token object to the queue.
484
    // There are currently two places where tokens will be submitted to the queue:
485
    // 1. When submitting a new task, if the token is still in the IDLE state,
486
    //    or the concurrency of the token has not reached the online level, it will be added to the queue.
487
    // 2. When the dispatch thread finishes executing a task:
488
    //    1. If it is a SERIAL token, and there are unsubmitted tasks, submit them to the queue.
489
    //    2. If it is a CONCURRENT token, and there are still unsubmitted tasks, and the upper limit of concurrency is not reached,
490
    //       then submitted to the queue.
491
5.51k
    if (token->need_dispatch()) {
492
4.39k
        _queue.emplace_back(token);
493
4.39k
        ++token->_num_submitted_tasks;
494
4.39k
        if (state == ThreadPoolToken::State::IDLE) {
495
2.64k
            token->transition(ThreadPoolToken::State::RUNNING);
496
2.64k
        }
497
4.39k
    } else {
498
1.11k
        ++token->_num_unsubmitted_tasks;
499
1.11k
    }
500
5.51k
    _total_queued_tasks++;
501
502
    // Wake up an idle thread for this task. Choosing the thread at the front of
503
    // the list ensures LIFO semantics as idling threads are also added to the front.
504
    //
505
    // If there are no idle threads, the new task remains on the queue and is
506
    // processed by an active thread (or a thread we're about to create) at some
507
    // point in the future.
508
5.51k
    if (!_idle_threads.empty()) {
509
1.69k
        _idle_threads.front().not_empty.notify_one();
510
1.69k
        _idle_threads.pop_front();
511
1.69k
    }
512
5.51k
    l.unlock();
513
514
5.51k
    if (need_a_thread) {
515
624
        Status status = create_thread();
516
624
        if (!status.ok()) {
517
0
            l.lock();
518
0
            _num_threads_pending_start--;
519
0
            if (_num_threads + _num_threads_pending_start == 0) {
520
                // If we have no threads, we can't do any work.
521
0
                return status;
522
0
            }
523
            // If we failed to create a thread, but there are still some other
524
            // worker threads, log a warning message and continue.
525
0
            LOG(WARNING) << "Thread pool " << _name
526
0
                         << " failed to create thread: " << status.to_string();
527
0
        }
528
624
    }
529
530
5.51k
    return Status::OK();
531
5.51k
}
532
533
100
void ThreadPool::wait() {
534
100
    std::unique_lock<std::mutex> l(_lock);
535
100
    check_not_pool_thread_unlocked();
536
200
    _idle_cond.wait(l, [this]() { return _total_queued_tasks == 0 && _active_threads == 0; });
537
100
}
538
539
1.49k
void ThreadPool::dispatch_thread() {
540
1.49k
    std::unique_lock<std::mutex> l(_lock);
541
1.49k
    debug::ScopedTSANIgnoreReadsAndWrites ignore_tsan;
542
1.49k
    InsertOrDie(&_threads, Thread::current_thread());
543
1.49k
    DCHECK_GT(_num_threads_pending_start, 0);
544
1.49k
    _num_threads++;
545
1.49k
    _num_threads_pending_start--;
546
547
1.49k
    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
1.49k
    IdleThread me;
553
554
477k
    while (true) {
555
        // Note: Status::Aborted() is used to indicate normal shutdown.
556
477k
        if (!_pool_status.ok()) {
557
944
            VLOG_CRITICAL << "DispatchThread exiting: " << _pool_status.to_string();
558
944
            break;
559
944
        }
560
561
476k
        if (_num_threads + _num_threads_pending_start > _max_threads) {
562
2
            break;
563
2
        }
564
565
476k
        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
472k
            _idle_threads.push_front(me);
570
472k
            SCOPED_CLEANUP({
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
472k
                if (me.is_linked()) {
575
472k
                    _idle_threads.erase(_idle_threads.iterator_to(me));
576
472k
                }
577
472k
            });
578
472k
            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
470k
                if (_queue.empty() && _num_threads + _num_threads_pending_start > _min_threads) {
586
506
                    VLOG_NOTICE << "Releasing worker thread from pool " << _name << " after "
587
0
                                << std::chrono::duration_cast<std::chrono::milliseconds>(
588
0
                                           _idle_timeout)
589
0
                                           .count()
590
0
                                << "ms of idle time.";
591
506
                    break;
592
506
                }
593
470k
            }
594
472k
            continue;
595
472k
        }
596
597
4.42k
        MonotonicStopWatch task_execution_time_watch;
598
4.42k
        task_execution_time_watch.start();
599
        // Get the next token and task to execute.
600
4.42k
        ThreadPoolToken* token = _queue.front();
601
4.42k
        _queue.pop_front();
602
4.42k
        DCHECK_EQ(ThreadPoolToken::State::RUNNING, token->state());
603
4.42k
        DCHECK(!token->_entries.empty());
604
4.42k
        Task task = std::move(token->_entries.front());
605
4.42k
        thread_pool_task_wait_worker_time_ns_total->increment(
606
4.42k
                task.submit_time_wather.elapsed_time());
607
4.42k
        thread_pool_task_wait_worker_count_total->increment(1);
608
4.42k
        token->_entries.pop_front();
609
4.42k
        token->_active_threads++;
610
4.42k
        --_total_queued_tasks;
611
4.42k
        ++_active_threads;
612
613
4.42k
        l.unlock();
614
615
        // Execute the task
616
4.42k
        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
4.42k
        task.runnable.reset();
624
4.42k
        l.lock();
625
4.42k
        thread_pool_task_execution_time_ns_total->increment(
626
4.42k
                task_execution_time_watch.elapsed_time());
627
4.42k
        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
4.42k
        ThreadPoolToken::State state = token->state();
633
4.42k
        DCHECK(state == ThreadPoolToken::State::RUNNING ||
634
4.42k
               state == ThreadPoolToken::State::QUIESCING);
635
4.42k
        --token->_active_threads;
636
4.42k
        --token->_num_submitted_tasks;
637
638
        // handle shutdown && idle
639
4.42k
        if (token->_active_threads == 0) {
640
3.21k
            if (state == ThreadPoolToken::State::QUIESCING) {
641
567
                DCHECK(token->_entries.empty());
642
567
                token->transition(ThreadPoolToken::State::QUIESCED);
643
2.64k
            } else if (token->_entries.empty()) {
644
1.77k
                token->transition(ThreadPoolToken::State::IDLE);
645
1.77k
            }
646
3.21k
        }
647
648
        // We decrease _num_submitted_tasks holding lock, so the following DCHECK works.
649
4.42k
        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
4.42k
        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
704
            _queue.emplace_back(token);
658
704
            ++token->_num_submitted_tasks;
659
704
            --token->_num_unsubmitted_tasks;
660
704
        }
661
662
4.42k
        if (--_active_threads == 0) {
663
874
            _idle_cond.notify_all();
664
874
        }
665
4.42k
    }
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
1.49k
    CHECK(l.owns_lock());
671
672
1.49k
    CHECK_EQ(_threads.erase(Thread::current_thread()), 1);
673
1.49k
    _num_threads--;
674
1.49k
    if (_num_threads + _num_threads_pending_start == 0) {
675
749
        _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
749
        CHECK(_queue.empty());
680
749
        DCHECK_EQ(0, _total_queued_tasks);
681
749
    }
682
1.49k
}
683
684
1.49k
Status ThreadPool::create_thread() {
685
1.49k
    return Thread::create("thread pool", strings::Substitute("$0 [worker]", _name),
686
1.49k
                          &ThreadPool::dispatch_thread, this, nullptr);
687
1.49k
}
688
689
4.65k
void ThreadPool::check_not_pool_thread_unlocked() {
690
4.65k
    Thread* current = Thread::current_thread();
691
4.65k
    if (ContainsKey(_threads, 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
4.65k
}
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
7
Status ThreadPool::set_max_threads(int max_threads) {
714
7
    std::lock_guard<std::mutex> l(_lock);
715
7
    if (_min_threads > max_threads) {
716
        // max threads can not be set less than min threads
717
1
        return Status::InternalError("set thread pool {} max_threads failed", _name);
718
1
    }
719
720
6
    _max_threads = max_threads;
721
6
    if (_max_threads > _num_threads + _num_threads_pending_start) {
722
4
        int addition_threads = _max_threads - _num_threads - _num_threads_pending_start;
723
4
        addition_threads = std::min(addition_threads, _total_queued_tasks);
724
4
        RETURN_IF_ERROR(try_create_thread(addition_threads, l));
725
4
    }
726
6
    return Status::OK();
727
6
}
728
729
0
std::ostream& operator<<(std::ostream& o, ThreadPoolToken::State s) {
730
0
    return o << ThreadPoolToken::state_to_string(s);
731
0
}
732
733
} // namespace doris