2 Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
6 * @file CxxUtils/CachedPointer.icc
7 * @author scott snyder <snyder@bnl.gov>
8 * @date Nov, 2017, from earlier code in AthLinks.
9 * @brief Cached pointer with atomic update.
17 * @brief Default constructor. Sets the element to null.
21 CachedPointer<T>::CachedPointer()
28 * @brief Constructor from an element.
32 CachedPointer<T>::CachedPointer (pointer_t elt)
39 * @brief Copy constructor.
43 CachedPointer<T>::CachedPointer (const CachedPointer& other) noexcept
49 * @brief Move constructor.
53 CachedPointer<T>::CachedPointer ( CachedPointer&& other) noexcept
56 //Does not own pointer so don't need to null
67 CachedPointer<T>::operator= (const CachedPointer& other)
77 * @brief Set the element, assuming it is currently null.
78 * @param elt The new value for the element.
80 * The current value of the element must either be null, in which case,
81 * it is set to ELT, or else it must already be equal to ELT, in which
82 * case no write occurs. Anything else is considered an error.
84 * The reason for doing things this way is that we (have to) allow
85 * a pointer to the underlying element to escape to user code, and we
86 * don't want a write to conflict with a non-atomic read. (Such a read
87 * can only happen after the element has been set for the first time.)
91 void CachedPointer<T>::set (pointer_t elt) const
93 // Set the element to ELT if it is currently null.
94 pointer_t null = nullptr;
95 m_a.compare_exchange_strong (null, elt, std::memory_order_relaxed);
96 // If the element was originally null, then NULL will still be null.
97 // If the element was originally ELT, then no write will have been performed,
98 // and NULL will be ELT. If the element was originally something else,
99 // then NULL will be set to that value.
100 assert (null == nullptr || null == elt);
105 * @brief Store a new value to the element.
109 void CachedPointer<T>::store (pointer_t elt)
111 m_a.store (elt, std::memory_order_relaxed);
116 * @brief Return the current value of the element.
120 typename CachedPointer<T>::pointer_t
121 CachedPointer<T>::get() const
123 return m_a.load (std::memory_order_relaxed);
128 * @brief Return a pointer to the cached element.
132 const typename CachedPointer<T>::pointer_t*
133 CachedPointer<T>::ptr() const
139 } // namespace CxxUtils