extending_cas_based_arithmetic.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Distributed under the Boost Software License, Version 1.0.
  3. * (See accompanying file LICENSE_1_0.txt or copy at
  4. * http://www.boost.org/LICENSE_1_0.txt)
  5. *
  6. * Copyright (c) 2014 Andrey Semashev
  7. */
  8. /*!
  9. * \file atomic/detail/extending_cas_based_arithmetic.hpp
  10. *
  11. * This header contains a boilerplate of core atomic operations that require sign/zero extension in arithmetic operations.
  12. */
  13. #ifndef BOOST_ATOMIC_DETAIL_EXTENDING_CAS_BASED_ARITHMETIC_HPP_INCLUDED_
  14. #define BOOST_ATOMIC_DETAIL_EXTENDING_CAS_BASED_ARITHMETIC_HPP_INCLUDED_
  15. #include <cstddef>
  16. #include <boost/memory_order.hpp>
  17. #include <boost/atomic/detail/config.hpp>
  18. #include <boost/atomic/detail/storage_traits.hpp>
  19. #include <boost/atomic/detail/integral_conversions.hpp>
  20. #include <boost/atomic/detail/header.hpp>
  21. #ifdef BOOST_HAS_PRAGMA_ONCE
  22. #pragma once
  23. #endif
  24. namespace boost {
  25. namespace atomics {
  26. namespace detail {
  27. template< typename Base, std::size_t Size, bool Signed >
  28. struct extending_cas_based_arithmetic :
  29. public Base
  30. {
  31. typedef typename Base::storage_type storage_type;
  32. typedef typename storage_traits< Size >::type emulated_storage_type;
  33. static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
  34. {
  35. storage_type old_val;
  36. atomics::detail::non_atomic_load(storage, old_val);
  37. storage_type new_val;
  38. do
  39. {
  40. new_val = atomics::detail::integral_extend< Signed, storage_type >(static_cast< emulated_storage_type >(old_val + v));
  41. }
  42. while (!Base::compare_exchange_weak(storage, old_val, new_val, order, memory_order_relaxed));
  43. return old_val;
  44. }
  45. static BOOST_FORCEINLINE storage_type fetch_sub(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
  46. {
  47. storage_type old_val;
  48. atomics::detail::non_atomic_load(storage, old_val);
  49. storage_type new_val;
  50. do
  51. {
  52. new_val = atomics::detail::integral_extend< Signed, storage_type >(static_cast< emulated_storage_type >(old_val - v));
  53. }
  54. while (!Base::compare_exchange_weak(storage, old_val, new_val, order, memory_order_relaxed));
  55. return old_val;
  56. }
  57. };
  58. } // namespace detail
  59. } // namespace atomics
  60. } // namespace boost
  61. #include <boost/atomic/detail/footer.hpp>
  62. #endif // BOOST_ATOMIC_DETAIL_EXTENDING_CAS_BASED_ARITHMETIC_HPP_INCLUDED_