Bitcoin Core  22.99.0
P2P Digital Currency
scheduler.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2020 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 <random.h>
8 #include <util/time.h>
9 
10 #include <assert.h>
11 #include <functional>
12 #include <utility>
13 
15 {
16 }
17 
19 {
20  assert(nThreadsServicingQueue == 0);
21  if (stopWhenEmpty) assert(taskQueue.empty());
22 }
23 
24 
26 {
27  WAIT_LOCK(newTaskMutex, lock);
28  ++nThreadsServicingQueue;
29 
30  // newTaskMutex is locked throughout this loop EXCEPT
31  // when the thread is waiting or when the user's function
32  // is called.
33  while (!shouldStop()) {
34  try {
35  while (!shouldStop() && taskQueue.empty()) {
36  // Wait until there is something to do.
37  newTaskScheduled.wait(lock);
38  }
39 
40  // Wait until either there is a new task, or until
41  // the time of the first item on the queue:
42 
43  while (!shouldStop() && !taskQueue.empty()) {
44  std::chrono::system_clock::time_point timeToWaitFor = taskQueue.begin()->first;
45  if (newTaskScheduled.wait_until(lock, timeToWaitFor) == std::cv_status::timeout) {
46  break; // Exit loop after timeout, it means we reached the time of the event
47  }
48  }
49 
50  // If there are multiple threads, the queue can empty while we're waiting (another
51  // thread may service the task we were waiting on).
52  if (shouldStop() || taskQueue.empty())
53  continue;
54 
55  Function f = taskQueue.begin()->second;
56  taskQueue.erase(taskQueue.begin());
57 
58  {
59  // Unlock before calling f, so it can reschedule itself or another task
60  // without deadlocking:
61  REVERSE_LOCK(lock);
62  f();
63  }
64  } catch (...) {
65  --nThreadsServicingQueue;
66  throw;
67  }
68  }
69  --nThreadsServicingQueue;
70  newTaskScheduled.notify_one();
71 }
72 
73 void CScheduler::schedule(CScheduler::Function f, std::chrono::system_clock::time_point t)
74 {
75  {
77  taskQueue.insert(std::make_pair(t, f));
78  }
79  newTaskScheduled.notify_one();
80 }
81 
82 void CScheduler::MockForward(std::chrono::seconds delta_seconds)
83 {
84  assert(delta_seconds > 0s && delta_seconds <= 1h);
85 
86  {
88 
89  // use temp_queue to maintain updated schedule
90  std::multimap<std::chrono::system_clock::time_point, Function> temp_queue;
91 
92  for (const auto& element : taskQueue) {
93  temp_queue.emplace_hint(temp_queue.cend(), element.first - delta_seconds, element.second);
94  }
95 
96  // point taskQueue to temp_queue
97  taskQueue = std::move(temp_queue);
98  }
99 
100  // notify that the taskQueue needs to be processed
101  newTaskScheduled.notify_one();
102 }
103 
104 static void Repeat(CScheduler& s, CScheduler::Function f, std::chrono::milliseconds delta)
105 {
106  f();
107  s.scheduleFromNow([=, &s] { Repeat(s, f, delta); }, delta);
108 }
109 
110 void CScheduler::scheduleEvery(CScheduler::Function f, std::chrono::milliseconds delta)
111 {
112  scheduleFromNow([=] { Repeat(*this, f, delta); }, delta);
113 }
114 
115 size_t CScheduler::getQueueInfo(std::chrono::system_clock::time_point& first,
116  std::chrono::system_clock::time_point& last) const
117 {
119  size_t result = taskQueue.size();
120  if (!taskQueue.empty()) {
121  first = taskQueue.begin()->first;
122  last = taskQueue.rbegin()->first;
123  }
124  return result;
125 }
126 
128 {
130  return nThreadsServicingQueue;
131 }
132 
133 
135 {
136  {
138  // Try to avoid scheduling too many copies here, but if we
139  // accidentally have two ProcessQueue's scheduled at once its
140  // not a big deal.
141  if (m_are_callbacks_running) return;
142  if (m_callbacks_pending.empty()) return;
143  }
144  m_pscheduler->schedule(std::bind(&SingleThreadedSchedulerClient::ProcessQueue, this), std::chrono::system_clock::now());
145 }
146 
148 {
149  std::function<void()> callback;
150  {
152  if (m_are_callbacks_running) return;
153  if (m_callbacks_pending.empty()) return;
154  m_are_callbacks_running = true;
155 
156  callback = std::move(m_callbacks_pending.front());
157  m_callbacks_pending.pop_front();
158  }
159 
160  // RAII the setting of fCallbacksRunning and calling MaybeScheduleProcessQueue
161  // to ensure both happen safely even if callback() throws.
162  struct RAIICallbacksRunning {
164  explicit RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}
165  ~RAIICallbacksRunning()
166  {
167  {
168  LOCK(instance->m_cs_callbacks_pending);
169  instance->m_are_callbacks_running = false;
170  }
171  instance->MaybeScheduleProcessQueue();
172  }
173  } raiicallbacksrunning(this);
174 
175  callback();
176 }
177 
178 void SingleThreadedSchedulerClient::AddToProcessQueue(std::function<void()> func)
179 {
181 
182  {
184  m_callbacks_pending.emplace_back(std::move(func));
185  }
187 }
188 
190 {
192  bool should_continue = true;
193  while (should_continue) {
194  ProcessQueue();
196  should_continue = !m_callbacks_pending.empty();
197  }
198 }
199 
201 {
203  return m_callbacks_pending.size();
204 }
CScheduler::newTaskScheduled
std::condition_variable newTaskScheduled
Definition: scheduler.h:99
CScheduler
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:33
CScheduler::MockForward
void MockForward(std::chrono::seconds delta_seconds)
Mock the scheduler to fast forward in time.
Definition: scheduler.cpp:82
assert
assert(!tx.IsCoinBase())
SingleThreadedSchedulerClient::m_pscheduler
CScheduler * m_pscheduler
Definition: scheduler.h:120
CScheduler::newTaskMutex
Mutex newTaskMutex
Definition: scheduler.h:98
REVERSE_LOCK
#define REVERSE_LOCK(g)
Definition: sync.h:221
CScheduler::CScheduler
CScheduler()
Definition: scheduler.cpp:14
SingleThreadedSchedulerClient::CallbacksPending
size_t CallbacksPending()
Definition: scheduler.cpp:200
SingleThreadedSchedulerClient::ProcessQueue
void ProcessQueue()
Definition: scheduler.cpp:147
CScheduler::~CScheduler
~CScheduler()
Definition: scheduler.cpp:18
scheduler.h
CScheduler::serviceQueue
void serviceQueue()
Services the queue 'forever'.
Definition: scheduler.cpp:25
CScheduler::getQueueInfo
size_t getQueueInfo(std::chrono::system_clock::time_point &first, std::chrono::system_clock::time_point &last) const
Returns number of tasks waiting to be serviced, and first and last task times.
Definition: scheduler.cpp:115
random.h
CScheduler::Function
std::function< void()> Function
Definition: scheduler.h:41
time.h
CScheduler::scheduleEvery
void scheduleEvery(Function f, std::chrono::milliseconds delta)
Repeat f until the scheduler is stopped.
Definition: scheduler.cpp:110
Repeat
static void Repeat(CScheduler &s, CScheduler::Function f, std::chrono::milliseconds delta)
Definition: scheduler.cpp:104
SingleThreadedSchedulerClient::m_cs_callbacks_pending
RecursiveMutex m_cs_callbacks_pending
Definition: scheduler.h:122
SingleThreadedSchedulerClient::EmptyQueue
void EmptyQueue()
Processes all remaining queue members on the calling thread, blocking until queue is empty Must be ca...
Definition: scheduler.cpp:189
SingleThreadedSchedulerClient::AddToProcessQueue
void AddToProcessQueue(std::function< void()> func)
Add a callback to be executed.
Definition: scheduler.cpp:178
LOCK
#define LOCK(cs)
Definition: sync.h:226
CScheduler::shouldStop
bool shouldStop() const EXCLUSIVE_LOCKS_REQUIRED(newTaskMutex)
Definition: scheduler.h:104
SingleThreadedSchedulerClient::MaybeScheduleProcessQueue
void MaybeScheduleProcessQueue()
Definition: scheduler.cpp:134
CScheduler::scheduleFromNow
void scheduleFromNow(Function f, std::chrono::milliseconds delta)
Call f once after the delta has passed.
Definition: scheduler.h:47
SingleThreadedSchedulerClient
Class used by CScheduler clients which may schedule multiple jobs which are required to be run serial...
Definition: scheduler.h:117
CScheduler::AreThreadsServicingQueue
bool AreThreadsServicingQueue() const
Returns true if there are threads actively running in serviceQueue()
Definition: scheduler.cpp:127
CScheduler::schedule
void schedule(Function f, std::chrono::system_clock::time_point t)
Call func at/after time t.
Definition: scheduler.cpp:73
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:231