rippled
Loading...
Searching...
No Matches
basic_seconds_clock.cpp
1//------------------------------------------------------------------------------
2/*
3 This file is part of Beast: https://github.com/vinniefalco/Beast
4 Copyright 2021, Howard Hinnant <howard.hinnant@gmail.com>
5
6 Permission to use, copy, modify, and/or distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19
20#include <xrpl/beast/clock/basic_seconds_clock.h>
21#include <xrpl/beast/utility/instrumentation.h>
22
23#include <atomic>
24#include <chrono>
25#include <condition_variable>
26#include <mutex>
27#include <thread>
28
29namespace beast {
30
31namespace {
32
33// Updates the clock
34class seconds_clock_thread
35{
36 using Clock = basic_seconds_clock::Clock;
37
38 bool stop_;
39 std::mutex mut_;
41 std::thread thread_;
43
44public:
45 ~seconds_clock_thread();
46 seconds_clock_thread();
47
48 Clock::time_point
49 now();
50
51private:
52 void
53 run();
54};
55
57
58seconds_clock_thread::~seconds_clock_thread()
59{
60 XRPL_ASSERT(
61 thread_.joinable(),
62 "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable");
63 {
65 stop_ = true;
66 } // publish stop_ asap so if waiting thread times-out, it will see it
67 cv_.notify_one();
68 thread_.join();
69}
70
71seconds_clock_thread::seconds_clock_thread()
72 : stop_{false}, tp_{Clock::now().time_since_epoch().count()}
73{
74 thread_ = std::thread(&seconds_clock_thread::run, this);
75}
76
77seconds_clock_thread::Clock::time_point
78seconds_clock_thread::now()
79{
80 return Clock::time_point{Clock::duration{tp_.load()}};
81}
82
83void
84seconds_clock_thread::run()
85{
87 while (true)
88 {
89 using namespace std::chrono;
90
91 auto now = Clock::now();
92 tp_ = now.time_since_epoch().count();
93 auto const when = floor<seconds>(now) + 1s;
94 if (cv_.wait_until(lock, when, [this] { return stop_; }))
95 return;
96 }
97}
98
99} // unnamed namespace
100
101basic_seconds_clock::time_point
102basic_seconds_clock::now()
103{
104 static seconds_clock_thread clk;
105 return clk.now();
106}
107
108} // namespace beast
std::chrono::steady_clock Clock
T count(T... args)
T join(T... args)
T joinable(T... args)
T lock(T... args)
int run(int argc, char **argv)
Definition: Main.cpp:343