ops_extending_cas_based.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/ops_extending_cas_based.hpp
  10. *
  11. * This header contains a boilerplate of the \c operations template implementation that requires sign/zero extension in arithmetic operations.
  12. */
  13. #ifndef BOOST_ATOMIC_DETAIL_OPS_EXTENDING_CAS_BASED_HPP_INCLUDED_
  14. #define BOOST_ATOMIC_DETAIL_OPS_EXTENDING_CAS_BASED_HPP_INCLUDED_
  15. #include <cstddef>
  16. #include <boost/memory_order.hpp>
  17. #include <boost/atomic/detail/config.hpp>
  18. #include <boost/atomic/detail/storage_type.hpp>
  19. #include <boost/atomic/detail/integral_extend.hpp>
  20. #ifdef BOOST_HAS_PRAGMA_ONCE
  21. #pragma once
  22. #endif
  23. namespace boost {
  24. namespace atomics {
  25. namespace detail {
  26. template< typename Base, std::size_t Size, bool Signed >
  27. struct extending_cas_based_operations :
  28. public Base
  29. {
  30. typedef typename Base::storage_type storage_type;
  31. typedef typename make_storage_type< Size >::type emulated_storage_type;
  32. static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
  33. {
  34. storage_type old_val;
  35. atomics::detail::non_atomic_load(storage, old_val);
  36. storage_type new_val;
  37. do
  38. {
  39. new_val = atomics::detail::integral_extend< Signed, storage_type >(static_cast< emulated_storage_type >(old_val + v));
  40. }
  41. while (!Base::compare_exchange_weak(storage, old_val, new_val, order, memory_order_relaxed));
  42. return old_val;
  43. }
  44. static BOOST_FORCEINLINE storage_type fetch_sub(storage_type volatile& storage, storage_type v, memory_order order) BOOST_NOEXCEPT
  45. {
  46. storage_type old_val;
  47. atomics::detail::non_atomic_load(storage, old_val);
  48. storage_type new_val;
  49. do
  50. {
  51. new_val = atomics::detail::integral_extend< Signed, storage_type >(static_cast< emulated_storage_type >(old_val - v));
  52. }
  53. while (!Base::compare_exchange_weak(storage, old_val, new_val, order, memory_order_relaxed));
  54. return old_val;
  55. }
  56. };
  57. } // namespace detail
  58. } // namespace atomics
  59. } // namespace boost
  60. #endif // BOOST_ATOMIC_DETAIL_OPS_EXTENDING_CAS_BASED_HPP_INCLUDED_