Coverage Report

Created: 2025-06-10 13:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/checkqueue.h
Line
Count
Source
1
// Copyright (c) 2012-2022 The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#ifndef BITCOIN_CHECKQUEUE_H
6
#define BITCOIN_CHECKQUEUE_H
7
8
#include <logging.h>
9
#include <sync.h>
10
#include <tinyformat.h>
11
#include <util/threadnames.h>
12
13
#include <algorithm>
14
#include <iterator>
15
#include <optional>
16
#include <vector>
17
18
/**
19
 * Queue for verifications that have to be performed.
20
  * The verifications are represented by a type T, which must provide an
21
  * operator(), returning an std::optional<R>.
22
  *
23
  * The overall result of the computation is std::nullopt if all invocations
24
  * return std::nullopt, or one of the other results otherwise.
25
  *
26
  * One thread (the master) is assumed to push batches of verifications
27
  * onto the queue, where they are processed by N-1 worker threads. When
28
  * the master is done adding work, it temporarily joins the worker pool
29
  * as an N'th worker, until all jobs are done.
30
  *
31
  */
32
template <typename T, typename R = std::remove_cvref_t<decltype(std::declval<T>()().value())>>
33
class CCheckQueue
34
{
35
private:
36
    //! Mutex to protect the inner state
37
    Mutex m_mutex;
38
39
    //! Worker threads block on this when out of work
40
    std::condition_variable m_worker_cv;
41
42
    //! Master thread blocks on this when out of work
43
    std::condition_variable m_master_cv;
44
45
    //! The queue of elements to be processed.
46
    //! As the order of booleans doesn't matter, it is used as a LIFO (stack)
47
    std::vector<T> queue GUARDED_BY(m_mutex);
48
49
    //! The number of workers (including the master) that are idle.
50
    int nIdle GUARDED_BY(m_mutex){0};
51
52
    //! The total number of workers (including the master).
53
    int nTotal GUARDED_BY(m_mutex){0};
54
55
    //! The temporary evaluation result.
56
    std::optional<R> m_result GUARDED_BY(m_mutex);
57
58
    /**
59
     * Number of verifications that haven't completed yet.
60
     * This includes elements that are no longer queued, but still in the
61
     * worker's own batches.
62
     */
63
    unsigned int nTodo GUARDED_BY(m_mutex){0};
64
65
    //! The maximum number of elements to be processed in one batch
66
    const unsigned int nBatchSize;
67
68
    std::vector<std::thread> m_worker_threads;
69
    bool m_request_stop GUARDED_BY(m_mutex){false};
70
71
    /** Internal function that does bulk of the verification work. If fMaster, return the final result. */
72
    std::optional<R> Loop(bool fMaster) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
73
2.26M
    {
74
2.26M
        std::condition_variable& cond = fMaster ? m_master_cv : m_worker_cv;
  Branch (74:41): [True: 2.22M, False: 33.2k]
75
2.26M
        std::vector<T> vChecks;
76
2.26M
        vChecks.reserve(nBatchSize);
77
2.26M
        unsigned int nNow = 0;
78
2.26M
        std::optional<R> local_result;
79
2.26M
        bool do_work;
80
2.27M
        do {
81
2.27M
            {
82
2.27M
                WAIT_LOCK(m_mutex, lock);
83
                // first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
84
2.27M
                if (nNow) {
  Branch (84:21): [True: 16.3k, False: 2.26M]
85
16.3k
                    if (local_result.has_value() && !m_result.has_value()) {
  Branch (85:25): [True: 279, False: 16.0k]
  Branch (85:53): [True: 237, False: 42]
86
237
                        std::swap(local_result, m_result);
87
237
                    }
88
16.3k
                    nTodo -= nNow;
89
16.3k
                    if (nTodo == 0 && !fMaster) {
  Branch (89:25): [True: 7.06k, False: 9.27k]
  Branch (89:39): [True: 6.79k, False: 269]
90
                        // We processed the last element; inform the master it can exit and return the result
91
6.79k
                        m_master_cv.notify_one();
92
6.79k
                    }
93
2.26M
                } else {
94
                    // first iteration
95
2.26M
                    nTotal++;
96
2.26M
                }
97
                // logically, the do loop starts here
98
2.32M
                while (queue.empty() && !m_request_stop) {
  Branch (98:24): [True: 2.30M, False: 16.1k]
  Branch (98:41): [True: 2.27M, False: 33.2k]
99
2.27M
                    if (fMaster && nTodo == 0) {
  Branch (99:25): [True: 2.22M, False: 47.4k]
  Branch (99:36): [True: 2.22M, False: 712]
100
2.22M
                        nTotal--;
101
2.22M
                        std::optional<R> to_return = std::move(m_result);
102
                        // reset the status for new work later
103
2.22M
                        m_result = std::nullopt;
104
                        // return the current status
105
2.22M
                        return to_return;
106
2.22M
                    }
107
48.1k
                    nIdle++;
108
48.1k
                    cond.wait(lock); // wait
109
48.1k
                    nIdle--;
110
48.1k
                }
111
49.4k
                if (m_request_stop) {
  Branch (111:21): [True: 33.2k, False: 16.1k]
112
                    // return value does not matter, because m_request_stop is only set in the destructor.
113
33.2k
                    return std::nullopt;
114
33.2k
                }
115
116
                // Decide how many work units to process now.
117
                // * Do not try to do everything at once, but aim for increasingly smaller batches so
118
                //   all workers finish approximately simultaneously.
119
                // * Try to account for idle jobs which will instantly start helping.
120
                // * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
121
16.1k
                nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
122
16.1k
                auto start_it = queue.end() - nNow;
123
16.1k
                vChecks.assign(std::make_move_iterator(start_it), std::make_move_iterator(queue.end()));
124
16.1k
                queue.erase(start_it, queue.end());
125
                // Check whether we need to do work at all
126
16.1k
                do_work = !m_result.has_value();
127
16.1k
            }
128
            // execute work
129
16.1k
            if (do_work) {
  Branch (129:17): [True: 16.0k, False: 166]
130
16.0k
                for (T& check : vChecks) {
  Branch (130:31): [True: 16.0k, False: 15.7k]
131
16.0k
                    local_result = check();
132
16.0k
                    if (local_result.has_value()) break;
  Branch (132:25): [True: 253, False: 15.7k]
133
16.0k
                }
134
16.0k
            }
135
16.1k
            vChecks.clear();
136
16.1k
        } while (true);
  Branch (136:18): [Folded - Ignored]
137
2.26M
    }
138
139
public:
140
    //! Mutex to ensure only one concurrent CCheckQueueControl
141
    Mutex m_control_mutex;
142
143
    //! Create a new check queue
144
    explicit CCheckQueue(unsigned int batch_size, int worker_threads_num)
145
11.0k
        : nBatchSize(batch_size)
146
11.0k
    {
147
11.0k
        LogInfo("Script verification uses %d additional threads", worker_threads_num);
148
11.0k
        m_worker_threads.reserve(worker_threads_num);
149
44.3k
        for (int n = 0; n < worker_threads_num; ++n) {
  Branch (149:25): [True: 33.2k, False: 11.0k]
150
33.2k
            m_worker_threads.emplace_back([this, n]() {
151
33.2k
                util::ThreadRename(strprintf("scriptch.%i", n));
152
33.2k
                Loop(false /* worker thread */);
153
33.2k
            });
154
33.2k
        }
155
11.0k
    }
156
157
    // Since this class manages its own resources, which is a thread
158
    // pool `m_worker_threads`, copy and move operations are not appropriate.
159
    CCheckQueue(const CCheckQueue&) = delete;
160
    CCheckQueue& operator=(const CCheckQueue&) = delete;
161
    CCheckQueue(CCheckQueue&&) = delete;
162
    CCheckQueue& operator=(CCheckQueue&&) = delete;
163
164
    //! Join the execution until completion. If at least one evaluation wasn't successful, return
165
    //! its error.
166
    std::optional<R> Complete() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
167
2.22M
    {
168
2.22M
        return Loop(true /* master thread */);
169
2.22M
    }
170
171
    //! Add a batch of checks to the queue
172
    void Add(std::vector<T>&& vChecks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
173
20.2k
    {
174
20.2k
        if (vChecks.empty()) {
  Branch (174:13): [True: 5.00k, False: 15.2k]
175
5.00k
            return;
176
5.00k
        }
177
178
15.2k
        {
179
15.2k
            LOCK(m_mutex);
180
15.2k
            queue.insert(queue.end(), std::make_move_iterator(vChecks.begin()), std::make_move_iterator(vChecks.end()));
181
15.2k
            nTodo += vChecks.size();
182
15.2k
        }
183
184
15.2k
        if (vChecks.size() == 1) {
  Branch (184:13): [True: 14.6k, False: 678]
185
14.6k
            m_worker_cv.notify_one();
186
14.6k
        } else {
187
678
            m_worker_cv.notify_all();
188
678
        }
189
15.2k
    }
190
191
    ~CCheckQueue()
192
11.0k
    {
193
11.0k
        WITH_LOCK(m_mutex, m_request_stop = true);
194
11.0k
        m_worker_cv.notify_all();
195
33.2k
        for (std::thread& t : m_worker_threads) {
  Branch (195:29): [True: 33.2k, False: 11.0k]
196
33.2k
            t.join();
197
33.2k
        }
198
11.0k
    }
199
200
2.22M
    bool HasThreads() const { return !m_worker_threads.empty(); }
201
};
202
203
/**
204
 * RAII-style controller object for a CCheckQueue that guarantees the passed
205
 * queue is finished before continuing.
206
 */
207
template <typename T, typename R = std::remove_cvref_t<decltype(std::declval<T>()().value())>>
208
class SCOPED_LOCKABLE CCheckQueueControl
209
{
210
private:
211
    CCheckQueue<T, R>& m_queue;
212
    UniqueLock<Mutex> m_lock;
213
    bool fDone;
214
215
public:
216
    CCheckQueueControl() = delete;
217
    CCheckQueueControl(const CCheckQueueControl&) = delete;
218
    CCheckQueueControl& operator=(const CCheckQueueControl&) = delete;
219
2.22M
    explicit CCheckQueueControl(CCheckQueue<T>& queueIn) EXCLUSIVE_LOCK_FUNCTION(queueIn.m_control_mutex) : m_queue(queueIn), m_lock(LOCK_ARGS(queueIn.m_control_mutex)), fDone(false) {}
220
221
    std::optional<R> Complete()
222
2.22M
    {
223
2.22M
        auto ret = m_queue.Complete();
224
2.22M
        fDone = true;
225
2.22M
        return ret;
226
2.22M
    }
227
228
    void Add(std::vector<T>&& vChecks)
229
20.2k
    {
230
20.2k
        m_queue.Add(std::move(vChecks));
231
20.2k
    }
232
233
    ~CCheckQueueControl() UNLOCK_FUNCTION()
234
2.22M
    {
235
2.22M
        if (!fDone)
  Branch (235:13): [True: 0, False: 2.22M]
236
0
            Complete();
237
2.22M
    }
238
};
239
240
#endif // BITCOIN_CHECKQUEUE_H