Coverage Report

Created: 2024-08-21 05:08

/workdir/bitcoin/src/scheduler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2015-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
#include <scheduler.h>
6
7
#include <sync.h>
8
#include <util/time.h>
9
10
#include <cassert>
11
#include <functional>
12
#include <utility>
13
14
0
CScheduler::CScheduler() = default;
15
16
CScheduler::~CScheduler()
17
1
{
18
1
    assert(nThreadsServicingQueue == 0);
19
1
    if (stopWhenEmpty) assert(taskQueue.empty());
  Branch (19:9): [True: 0, False: 1]
20
1
}
21
22
23
void CScheduler::serviceQueue()
24
0
{
25
0
    WAIT_LOCK(newTaskMutex, lock);
26
0
    ++nThreadsServicingQueue;
27
28
    // newTaskMutex is locked throughout this loop EXCEPT
29
    // when the thread is waiting or when the user's function
30
    // is called.
31
291
    while (!shouldStop()) {
  Branch (31:12): [True: 290, False: 1]
32
290
        try {
33
580
            while (!shouldStop() && taskQueue.empty()) {
  Branch (33:20): [True: 580, False: 0]
  Branch (33:37): [True: 290, False: 290]
34
                // Wait until there is something to do.
35
290
                newTaskScheduled.wait(lock);
36
290
            }
37
38
            // Wait until either there is a new task, or until
39
            // the time of the first item on the queue:
40
41
290
            while (!shouldStop() && !taskQueue.empty()) {
  Branch (41:20): [True: 290, False: 0]
  Branch (41:37): [True: 290, False: 0]
42
290
                std::chrono::steady_clock::time_point timeToWaitFor = taskQueue.begin()->first;
43
290
                if (newTaskScheduled.wait_until(lock, timeToWaitFor) == std::cv_status::timeout) {
  Branch (43:21): [True: 290, False: 0]
44
290
                    break; // Exit loop after timeout, it means we reached the time of the event
45
290
                }
46
290
            }
47
48
            // If there are multiple threads, the queue can empty while we're waiting (another
49
            // thread may service the task we were waiting on).
50
290
            if (shouldStop() || taskQueue.empty())
  Branch (50:17): [True: 0, False: 290]
  Branch (50:33): [True: 0, False: 290]
51
1
                continue;
52
53
289
            Function f = taskQueue.begin()->second;
54
289
            taskQueue.erase(taskQueue.begin());
55
56
289
            {
57
                // Unlock before calling f, so it can reschedule itself or another task
58
                // without deadlocking:
59
289
                REVERSE_LOCK(lock);
60
289
                f();
61
289
            }
62
289
        } catch (...) {
63
0
            --nThreadsServicingQueue;
64
0
            throw;
65
0
        }
66
290
    }
67
1
    --nThreadsServicingQueue;
68
1
    newTaskScheduled.notify_one();
69
1
}
70
71
void CScheduler::schedule(CScheduler::Function f, std::chrono::steady_clock::time_point t)
72
290
{
73
290
    {
74
290
        LOCK(newTaskMutex);
75
290
        taskQueue.insert(std::make_pair(t, f));
76
290
    }
77
290
    newTaskScheduled.notify_one();
78
290
}
79
80
void CScheduler::MockForward(std::chrono::seconds delta_seconds)
81
0
{
82
0
    assert(delta_seconds > 0s && delta_seconds <= 1h);
83
84
0
    {
85
0
        LOCK(newTaskMutex);
86
87
        // use temp_queue to maintain updated schedule
88
0
        std::multimap<std::chrono::steady_clock::time_point, Function> temp_queue;
89
90
0
        for (const auto& element : taskQueue) {
  Branch (90:34): [True: 0, False: 0]
91
0
            temp_queue.emplace_hint(temp_queue.cend(), element.first - delta_seconds, element.second);
92
0
        }
93
94
        // point taskQueue to temp_queue
95
0
        taskQueue = std::move(temp_queue);
96
0
    }
97
98
    // notify that the taskQueue needs to be processed
99
0
    newTaskScheduled.notify_one();
100
0
}
101
102
static void Repeat(CScheduler& s, CScheduler::Function f, std::chrono::milliseconds delta)
103
0
{
104
0
    f();
105
0
    s.scheduleFromNow([=, &s] { Repeat(s, f, delta); }, delta);
106
0
}
107
108
void CScheduler::scheduleEvery(CScheduler::Function f, std::chrono::milliseconds delta)
109
0
{
110
0
    scheduleFromNow([this, f, delta] { Repeat(*this, f, delta); }, delta);
111
0
}
112
113
size_t CScheduler::getQueueInfo(std::chrono::steady_clock::time_point& first,
114
                                std::chrono::steady_clock::time_point& last) const
115
0
{
116
0
    LOCK(newTaskMutex);
117
0
    size_t result = taskQueue.size();
118
0
    if (!taskQueue.empty()) {
  Branch (118:9): [True: 0, False: 0]
119
0
        first = taskQueue.begin()->first;
120
0
        last = taskQueue.rbegin()->first;
121
0
    }
122
0
    return result;
123
0
}
124
125
bool CScheduler::AreThreadsServicingQueue() const
126
1
{
127
1
    LOCK(newTaskMutex);
128
1
    return nThreadsServicingQueue;
129
1
}
130
131
132
void SerialTaskRunner::MaybeScheduleProcessQueue()
133
580
{
134
580
    {
135
580
        LOCK(m_callbacks_mutex);
136
        // Try to avoid scheduling too many copies here, but if we
137
        // accidentally have two ProcessQueue's scheduled at once its
138
        // not a big deal.
139
580
        if (m_are_callbacks_running) return;
  Branch (139:13): [True: 0, False: 580]
140
580
        if (m_callbacks_pending.empty()) return;
  Branch (140:13): [True: 290, False: 290]
141
580
    }
142
290
    m_scheduler.schedule([this] { this->ProcessQueue(); }, std::chrono::steady_clock::now());
143
290
}
144
145
void SerialTaskRunner::ProcessQueue()
146
291
{
147
291
    std::function<void()> callback;
148
291
    {
149
291
        LOCK(m_callbacks_mutex);
150
291
        if (m_are_callbacks_running) return;
  Branch (150:13): [True: 0, False: 291]
151
291
        if (m_callbacks_pending.empty()) return;
  Branch (151:13): [True: 1, False: 290]
152
290
        m_are_callbacks_running = true;
153
154
290
        callback = std::move(m_callbacks_pending.front());
155
290
        m_callbacks_pending.pop_front();
156
290
    }
157
158
    // RAII the setting of fCallbacksRunning and calling MaybeScheduleProcessQueue
159
    // to ensure both happen safely even if callback() throws.
160
0
    struct RAIICallbacksRunning {
161
290
        SerialTaskRunner* instance;
162
290
        explicit RAIICallbacksRunning(SerialTaskRunner* _instance) : instance(_instance) {}
163
290
        ~RAIICallbacksRunning()
164
290
        {
165
290
            {
166
290
                LOCK(instance->m_callbacks_mutex);
167
290
                instance->m_are_callbacks_running = false;
168
290
            }
169
290
            instance->MaybeScheduleProcessQueue();
170
290
        }
171
290
    } raiicallbacksrunning(this);
172
173
290
    callback();
174
290
}
175
176
void SerialTaskRunner::insert(std::function<void()> func)
177
290
{
178
290
    {
179
290
        LOCK(m_callbacks_mutex);
180
290
        m_callbacks_pending.emplace_back(std::move(func));
181
290
    }
182
290
    MaybeScheduleProcessQueue();
183
290
}
184
185
void SerialTaskRunner::flush()
186
1
{
187
1
    assert(!m_scheduler.AreThreadsServicingQueue());
188
1
    bool should_continue = true;
189
2
    while (should_continue) {
  Branch (189:12): [True: 1, False: 1]
190
1
        ProcessQueue();
191
1
        LOCK(m_callbacks_mutex);
192
1
        should_continue = !m_callbacks_pending.empty();
193
1
    }
194
1
}
195
196
size_t SerialTaskRunner::size()
197
0
{
198
0
    LOCK(m_callbacks_mutex);
199
0
    return m_callbacks_pending.size();
200
0
}