From d2cf7c7a5c9c83e0607d2d7adf1d1e23192ae016 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Wed, 24 Jan 2024 14:30:04 +0200 Subject: [PATCH] BAN: Implement basic Atomic class that wraps gcc builtins --- BAN/include/BAN/Atomic.h | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 BAN/include/BAN/Atomic.h diff --git a/BAN/include/BAN/Atomic.h b/BAN/include/BAN/Atomic.h new file mode 100644 index 000000000..52a2ff7a0 --- /dev/null +++ b/BAN/include/BAN/Atomic.h @@ -0,0 +1,42 @@ +#pragma once + +namespace BAN +{ + + template + requires requires { __atomic_always_lock_free(sizeof(T), 0); } + class Atomic + { + Atomic(const Atomic&) = delete; + Atomic(Atomic&&) = delete; + Atomic& operator=(const Atomic&) volatile = delete; + Atomic& operator=(Atomic&&) volatile = delete; + + public: + constexpr Atomic() : m_value(0) {} + constexpr Atomic(T val) : m_value(val) {} + + inline T load() const volatile { return __atomic_load_n(&m_value, MEM_ORDER); } + inline void store(T val) volatile { __atomic_store_n(&m_value, val, MEM_ORDER); } + + inline T operator=(T val) volatile { store(val); return val; } + + inline operator T() const volatile { return load(); } + + inline T operator+=(T val) volatile { return __atomic_add_fetch(&m_value, val, MEM_ORDER); } + inline T operator-=(T val) volatile { return __atomic_sub_fetch(&m_value, val, MEM_ORDER); } + inline T operator&=(T val) volatile { return __atomic_and_fetch(&m_value, val, MEM_ORDER); } + inline T operator^=(T val) volatile { return __atomic_xor_fetch(&m_value, val, MEM_ORDER); } + inline T operator|=(T val) volatile { return __atomic_or_fetch(&m_value, val, MEM_ORDER); } + + inline T operator--() volatile { return __atomic_sub_fetch(&m_value, 1, MEM_ORDER); } + inline T operator++() volatile { return __atomic_add_fetch(&m_value, 1, MEM_ORDER); } + + inline T operator--(int) volatile { return __atomic_fetch_sub(&m_value, 1, MEM_ORDER); } + inline T operator++(int) volatile { return __atomic_fetch_add(&m_value, 1, MEM_ORDER); } + + private: + T m_value; + }; + +} \ No newline at end of file