atomic_count.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // detail/atomic_count.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP
  11. #define BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #if !defined(BOOST_ASIO_HAS_THREADS)
  17. // Nothing to include.
  18. #elif defined(BOOST_ASIO_HAS_STD_ATOMIC)
  19. # include <atomic>
  20. #else // defined(BOOST_ASIO_HAS_STD_ATOMIC)
  21. # include <boost/detail/atomic_count.hpp>
  22. #endif // defined(BOOST_ASIO_HAS_STD_ATOMIC)
  23. namespace boost {
  24. namespace asio {
  25. namespace detail {
  26. #if !defined(BOOST_ASIO_HAS_THREADS)
  27. typedef long atomic_count;
  28. inline void increment(atomic_count& a, long b) { a += b; }
  29. inline void ref_count_up(atomic_count& a) { ++a; }
  30. inline bool ref_count_down(atomic_count& a) { return --a == 0; }
  31. #elif defined(BOOST_ASIO_HAS_STD_ATOMIC)
  32. typedef std::atomic<long> atomic_count;
  33. inline void increment(atomic_count& a, long b) { a += b; }
  34. inline void ref_count_up(atomic_count& a)
  35. {
  36. a.fetch_add(1, std::memory_order_relaxed);
  37. }
  38. inline bool ref_count_down(atomic_count& a)
  39. {
  40. if (a.fetch_sub(1, std::memory_order_release) == 1)
  41. {
  42. std::atomic_thread_fence(std::memory_order_acquire);
  43. return true;
  44. }
  45. return false;
  46. }
  47. #else // defined(BOOST_ASIO_HAS_STD_ATOMIC)
  48. typedef boost::detail::atomic_count atomic_count;
  49. inline void increment(atomic_count& a, long b) { while (b > 0) ++a, --b; }
  50. inline void ref_count_up(atomic_count& a) { ++a; }
  51. inline bool ref_count_down(atomic_count& a) { return --a == 0; }
  52. #endif // defined(BOOST_ASIO_HAS_STD_ATOMIC)
  53. } // namespace detail
  54. } // namespace asio
  55. } // namespace boost
  56. #endif // BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP