icinga2/lib/base/atomic.hpp
Julian Brost 33b5ed85fe Remove obsolete workaround for GCC 4.x
The fallback implementation was added for GCC 4.x as that didn't yet implement
std::is_trivially_copyable. However, by now we're using C++17 as our language
standard and that wasn't even implemented in GCC 4.x yet[^1]:

    Some C++17 features are available since GCC 5, but support was experimental
    and the ABI of C++17 features was not stable until GCC 9.

Hence, this became more or less dead code and can be removed.

[^1]: https://gcc.gnu.org/projects/cxx-status.html#cxx17
2025-09-05 10:24:25 +02:00

79 lines
1.6 KiB
C++

/* Icinga 2 | (c) 2019 Icinga GmbH | GPLv2+ */
#ifndef ATOMIC_H
#define ATOMIC_H
#include <atomic>
#include <mutex>
#include <type_traits>
#include <utility>
namespace icinga
{
/**
* Like std::atomic, but enforces usage of its only safe constructor.
*
* "The default-initialized std::atomic<T> does not contain a T object,
* and its only valid uses are destruction and
* initialization by std::atomic_init, see LWG issue 2334."
* -- https://en.cppreference.com/w/cpp/atomic/atomic/atomic
*
* @ingroup base
*/
template<class T>
class Atomic : public std::atomic<T> {
public:
/**
* The only safe constructor of std::atomic#atomic
*
* @param desired Initial value
*/
inline Atomic(T desired) : std::atomic<T>(desired)
{
}
};
/**
* Wraps any T into a std::atomic<T>-like interface that locks using a mutex.
*
* In contrast to std::atomic<T>, Locked<T> is also valid for types that are not trivially copyable.
* In case T is trivially copyable, std::atomic<T> is almost certainly the better choice.
*
* @ingroup base
*/
template<typename T>
class Locked
{
public:
inline T load() const
{
std::unique_lock<std::mutex> lock(m_Mutex);
return m_Value;
}
inline void store(T desired)
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Value = std::move(desired);
}
private:
mutable std::mutex m_Mutex;
T m_Value;
};
/**
* Type alias for std::atomic<T> if possible, otherwise Locked<T> is used as a fallback.
*
* @ingroup base
*/
template <typename T>
using AtomicOrLocked = typename std::conditional<std::is_trivially_copyable<T>::value, std::atomic<T>, Locked<T>>::type;
}
#endif /* ATOMIC_H */