Coverage Report

Created: 2026-08-08 07:05

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