Coverage Report

Created: 2026-09-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/brpc/src/bthread/task_control.h
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
18
// bthread - An M:N threading library to make applications more concurrent.
19
20
// Date: Tue Jul 10 17:40:58 CST 2012
21
22
#ifndef BTHREAD_TASK_CONTROL_H
23
#define BTHREAD_TASK_CONTROL_H
24
25
#ifndef NDEBUG
26
#include <iostream>                             // std::ostream
27
#endif
28
#include <signal.h>
29
#include <stddef.h>                             // size_t
30
#include <vector>
31
#include <array>
32
#include <memory>
33
#include "butil/atomicops.h"                     // butil::atomic
34
#include "bvar/bvar.h"                          // bvar::PassiveStatus
35
#include "bthread/task_tracer.h"
36
#include "bthread/task_meta.h"                  // TaskMeta
37
#include "bthread/work_stealing_queue.h"        // WorkStealingQueue
38
#include "bthread/parking_lot.h"
39
40
DECLARE_int32(task_group_ntags);
41
namespace bthread {
42
43
class TaskGroup;
44
struct CumulatedWithTagArgs;
45
46
// Control all task groups
47
class TaskControl {
48
friend class TaskGroup;
49
friend void wait_for_butex(void*);
50
#ifdef BRPC_BTHREAD_TRACER
51
friend bthread_t init_for_pthread_stack_trace();
52
#endif // BRPC_BTHREAD_TRACER
53
54
public:
55
    TaskControl();
56
    ~TaskControl();
57
58
    // Must be called before using. `nconcurrency' is # of worker pthreads.
59
    int init(int nconcurrency);
60
    
61
    // Create a TaskGroup in this control.
62
    TaskGroup* create_group(bthread_tag_t tag);
63
64
    // Steal a task from a "random" group.
65
    bool steal_task(bthread_t* tid, size_t* seed, size_t offset);
66
67
    // Tell other groups that `n' tasks was just added to caller's runqueue
68
    void signal_task(int num_task, bthread_tag_t tag);
69
70
    // Stop and join worker threads in TaskControl.
71
    void stop_and_join();
72
    
73
    // Get # of worker threads.
74
    int concurrency() const 
75
0
    { return _concurrency.load(butil::memory_order_acquire); }
76
77
    int concurrency(bthread_tag_t tag) const 
78
0
    { return _tagged_ngroup[tag].load(butil::memory_order_acquire); }
79
80
    void print_rq_sizes(std::ostream& os);
81
82
    double get_cumulated_worker_time();
83
    double get_cumulated_worker_time(bthread_tag_t tag);
84
    int64_t get_cumulated_switch_count();
85
    int64_t get_cumulated_signal_count();
86
87
    // [Not thread safe] Add more worker threads.
88
    // Return the number of workers actually added, which may be less than |num|
89
    int add_workers(int num, bthread_tag_t tag);
90
91
    // Choose one TaskGroup (randomly right now).
92
    // If this method is called after init(), it never returns nullptr.
93
    TaskGroup* choose_one_group(bthread_tag_t tag);
94
95
    // Parse FLAGS_cpu_set into _tag_cpus.  Two formats are accepted:
96
    //   Legacy (all tags share one set): "0-3,5,7"
97
    //   Per-tag:  "0:0-3,5,7;1:6-9,4"
98
    // Tags not mentioned get an empty cpu list (= no binding).
99
    // Returns -1 on parse error.
100
    int parse_cpuset(const std::string& value);
101
102
    static void bind_thread_to_cpu(pthread_t pthread, unsigned cpu_id);
103
104
#ifdef BRPC_BTHREAD_TRACER
105
    // A stacktrace of bthread can be helpful in debugging.
106
    void stack_trace(std::ostream& os, bthread_t tid);
107
    std::string stack_trace(bthread_t tid);
108
#endif // BRPC_BTHREAD_TRACER
109
110
    void push_ed_priority_queue(
111
0
            bthread_tag_t tag, int priority_index, bthread_t tid) {
112
0
        ed_priority_queue(tag, priority_index).push(tid);
113
0
    }
114
115
    std::vector<bthread_t> get_living_bthreads();
116
117
private:
118
    typedef std::array<TaskGroup*, BTHREAD_MAX_CONCURRENCY> TaggedGroups;
119
    typedef std::array<ParkingLot, BTHREAD_MAX_PARKINGLOT> TaggedParkingLot;
120
    // Add/Remove a TaskGroup.
121
    // Returns 0 on success, -1 otherwise.
122
    int _add_group(TaskGroup*, bthread_tag_t tag);
123
    int _destroy_group(TaskGroup*);
124
125
    // Tag group
126
0
    TaggedGroups& tag_group(bthread_tag_t tag) { return _tagged_groups[tag]; }
127
128
    // Tag ngroup
129
0
    butil::atomic<size_t>& tag_ngroup(int tag) { return _tagged_ngroup[tag]; }
130
131
    // Tag parking slot
132
0
    TaggedParkingLot& tag_pl(bthread_tag_t tag) { return _tagged_pl[tag]; }
133
134
    // Priority queue for a specific ED within a tag
135
    WorkStealingQueue<bthread_t>& ed_priority_queue(
136
0
            bthread_tag_t tag, int index) {
137
0
        return _ed_priority_queues[
138
0
            tag * _ed_priority_queue_num_of_each_tag + index];
139
0
    }
140
141
    int init_ed_priority_queues();
142
143
    static void delete_task_group(void* arg);
144
145
    static void* worker_thread(void* task_control);
146
147
    template <typename F>
148
    void for_each_task_group(F const& f);
149
150
    bvar::LatencyRecorder& exposed_pending_time();
151
    bvar::LatencyRecorder* create_exposed_pending_time();
152
    bvar::Adder<int64_t>& tag_nworkers(bthread_tag_t tag);
153
    bvar::Adder<int64_t>& tag_nbthreads(bthread_tag_t tag);
154
155
    std::vector<butil::atomic<size_t>> _tagged_ngroup;
156
    std::vector<TaggedGroups> _tagged_groups;
157
    butil::Mutex _modify_group_mutex;
158
159
    butil::atomic<bool> _init;  // if not init, bvar will case coredump
160
    bool _stop;
161
    butil::atomic<int> _concurrency;
162
    std::vector<pthread_t> _workers;
163
    bvar::Adder<int64_t> _nworkers;
164
    butil::Mutex _pending_time_mutex;
165
    butil::atomic<bvar::LatencyRecorder*> _pending_time;
166
    bvar::PassiveStatus<double> _cumulated_worker_time;
167
    bvar::PerSecond<bvar::PassiveStatus<double> > _worker_usage_second;
168
    bvar::PassiveStatus<int64_t> _cumulated_switch_count;
169
    bvar::PerSecond<bvar::PassiveStatus<int64_t> > _switch_per_second;
170
    bvar::PassiveStatus<int64_t> _cumulated_signal_count;
171
    bvar::PerSecond<bvar::PassiveStatus<int64_t> > _signal_per_second;
172
    bvar::PassiveStatus<std::string> _status;
173
    bvar::Adder<int64_t> _nbthreads;
174
175
    std::vector<std::unique_ptr<bvar::Adder<int64_t>>> _tagged_nworkers;
176
    std::vector<std::unique_ptr<CumulatedWithTagArgs>>
177
        _tagged_cumulated_worker_time_args;
178
    std::vector<std::unique_ptr<bvar::PassiveStatus<double>>>
179
        _tagged_cumulated_worker_time;
180
    std::vector<std::unique_ptr<bvar::PerSecond<bvar::PassiveStatus<double>>>>
181
        _tagged_worker_usage_second;
182
    std::vector<std::unique_ptr<bvar::Adder<int64_t>>> _tagged_nbthreads;
183
184
    bool _enable_priority_queue;
185
    int _ed_priority_queue_num_of_each_tag;
186
    std::vector<WorkStealingQueue<bthread_t>> _ed_priority_queues;
187
188
    size_t _pl_num_of_each_tag;
189
    std::vector<TaggedParkingLot> _tagged_pl;
190
    // Per-tag CPU binding lists.  _tag_cpus[tag] is the round-robin list of
191
    // CPU IDs to which workers of that tag are bound.  Empty means no binding.
192
    std::vector<std::vector<unsigned>> _tag_cpus;
193
    // Per-tag monotonic counter for round-robin CPU assignment.
194
    // Incremented once per worker created for that tag (in worker_thread).
195
    std::vector<butil::atomic<int>> _tag_next_worker_id;
196
197
#ifdef BRPC_BTHREAD_TRACER
198
    TaskTracer _task_tracer;
199
#endif // BRPC_BTHREAD_TRACER
200
201
};
202
203
0
inline bvar::LatencyRecorder& TaskControl::exposed_pending_time() {
204
0
    bvar::LatencyRecorder* pt = _pending_time.load(butil::memory_order_consume);
205
0
    if (!pt) {
206
0
        pt = create_exposed_pending_time();
207
0
    }
208
0
    return *pt;
209
0
}
210
211
0
inline bvar::Adder<int64_t>& TaskControl::tag_nworkers(bthread_tag_t tag) {
212
0
    return *_tagged_nworkers[tag];
213
0
}
214
215
0
inline bvar::Adder<int64_t>& TaskControl::tag_nbthreads(bthread_tag_t tag) {
216
0
    return *_tagged_nbthreads[tag];
217
0
}
218
219
template <typename F>
220
0
inline void TaskControl::for_each_task_group(F const& f) {
221
0
    if (_init.load(butil::memory_order_acquire) == false) {
222
0
        return;
223
0
    }
224
0
    for (size_t i = 0; i < _tagged_groups.size(); ++i) {
225
0
        auto ngroup = tag_ngroup(i).load(butil::memory_order_relaxed);
226
0
        auto& groups = tag_group(i);
227
0
        for (size_t j = 0; j < ngroup; ++j) {
228
0
            f(groups[j]);
229
0
        }
230
0
    }
231
0
}
Unexecuted instantiation: task_control.cpp:void bthread::TaskControl::for_each_task_group<bthread::TaskControl::print_rq_sizes(std::basic_ostream<char, std::char_traits<char> >&)::$_1>(bthread::TaskControl::print_rq_sizes(std::basic_ostream<char, std::char_traits<char> >&)::$_1 const&)
Unexecuted instantiation: task_control.cpp:void bthread::TaskControl::for_each_task_group<bthread::TaskControl::get_cumulated_worker_time()::$_0>(bthread::TaskControl::get_cumulated_worker_time()::$_0 const&)
Unexecuted instantiation: task_control.cpp:void bthread::TaskControl::for_each_task_group<bthread::TaskControl::get_cumulated_switch_count()::$_0>(bthread::TaskControl::get_cumulated_switch_count()::$_0 const&)
Unexecuted instantiation: task_control.cpp:void bthread::TaskControl::for_each_task_group<bthread::TaskControl::get_cumulated_signal_count()::$_0>(bthread::TaskControl::get_cumulated_signal_count()::$_0 const&)
232
233
}  // namespace bthread
234
235
#endif  // BTHREAD_TASK_CONTROL_H