Bitcoin ABC  0.22.13
P2P Digital Currency
eventloop.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020 The Bitcoin 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 <eventloop.h>
6 
7 #include <scheduler.h>
8 
10  stopEventLoop();
11 }
12 
14  std::function<void()> runEventLoop,
15  std::chrono::milliseconds delta) {
17  if (running) {
18  // Do not start the event loop twice.
19  return false;
20  }
21 
22  running = true;
23 
24  // Start the event loop.
25  scheduler.scheduleEvery(
26  [this, runEventLoop]() -> bool {
27  runEventLoop();
28  if (!stopRequest) {
29  return true;
30  }
31 
33  running = false;
34 
35  cond_running.notify_all();
36 
37  // A stop request was made.
38  return false;
39  },
40  delta);
41 
42  return true;
43 }
44 
46  WAIT_LOCK(cs_running, lock);
47  if (!running) {
48  return false;
49  }
50 
51  // Request event loop to stop.
52  stopRequest = true;
53 
54  // Wait for event loop to stop.
55  cond_running.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(cs_running) {
56  return !running;
57  });
58 
59  stopRequest = false;
60  return true;
61 }
Mutex cs_running
Definition: eventloop.h:34
#define LOCK(cs)
Definition: sync.h:230
void scheduleEvery(Predicate p, std::chrono::milliseconds delta)
Repeat p until it return false.
Definition: scheduler.cpp:127
bool stopEventLoop()
Definition: eventloop.cpp:45
std::atomic< bool > stopRequest
Start stop machinery.
Definition: eventloop.h:31
#define WAIT_LOCK(cs, name)
Definition: sync.h:238
~EventLoop()
Definition: eventloop.cpp:9
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
bool startEventLoop(CScheduler &scheduler, std::function< void()> runEventLoop, std::chrono::milliseconds delta)
Definition: eventloop.cpp:13
std::condition_variable cond_running
Definition: eventloop.h:35