Bitcoin Core  22.0.0
P2P Digital Currency
epochguard.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_UTIL_EPOCHGUARD_H
7 #define BITCOIN_UTIL_EPOCHGUARD_H
8 
9 #include <threadsafety.h>
10 
11 #include <cassert>
12 
34 {
35 private:
36  uint64_t m_raw_epoch = 0;
37  bool m_guarded = false;
38 
39 public:
40  Epoch() = default;
41  Epoch(const Epoch&) = delete;
42  Epoch& operator=(const Epoch&) = delete;
43 
44  bool guarded() const { return m_guarded; }
45 
46  class Marker
47  {
48  private:
49  uint64_t m_marker = 0;
50 
51  // only allow modification via Epoch member functions
52  friend class Epoch;
53  Marker& operator=(const Marker&) = delete;
54  };
55 
57  {
58  private:
60 
61  public:
62  explicit Guard(Epoch& epoch) EXCLUSIVE_LOCK_FUNCTION(epoch) : m_epoch(epoch)
63  {
64  assert(!m_epoch.m_guarded);
65  ++m_epoch.m_raw_epoch;
66  m_epoch.m_guarded = true;
67  }
69  {
70  assert(m_epoch.m_guarded);
71  ++m_epoch.m_raw_epoch; // ensure clear separation between epochs
72  m_epoch.m_guarded = false;
73  }
74  };
75 
76  bool visited(Marker& marker) const EXCLUSIVE_LOCKS_REQUIRED(*this)
77  {
78  assert(m_guarded);
79  if (marker.m_marker < m_raw_epoch) {
80  // marker is from a previous epoch, so this is its first visit
81  marker.m_marker = m_raw_epoch;
82  return false;
83  } else {
84  return true;
85  }
86  }
87 };
88 
89 #define WITH_FRESH_EPOCH(epoch) const Epoch::Guard PASTE2(epoch_guard_, __COUNTER__)(epoch)
90 
91 #endif // BITCOIN_UTIL_EPOCHGUARD_H
#define EXCLUSIVE_LOCK_FUNCTION(...)
Definition: threadsafety.h:42
assert(!tx.IsCoinBase())
Epoch & operator=(const Epoch &)=delete
~Guard() UNLOCK_FUNCTION()
Definition: epochguard.h:68
uint64_t m_raw_epoch
Definition: epochguard.h:36
#define UNLOCK_FUNCTION(...)
Definition: threadsafety.h:46
Guard(Epoch &epoch) EXCLUSIVE_LOCK_FUNCTION(epoch)
Definition: epochguard.h:62
Epoch & m_epoch
Definition: epochguard.h:59
bool guarded() const
Definition: epochguard.h:44
#define LOCKABLE
Definition: threadsafety.h:36
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
bool visited(Marker &marker) const EXCLUSIVE_LOCKS_REQUIRED(*this)
Definition: epochguard.h:76
bool m_guarded
Definition: epochguard.h:37
#define SCOPED_LOCKABLE
Definition: threadsafety.h:37
Epoch: RAII-style guard for using epoch-based graph traversal algorithms.
Definition: epochguard.h:33