atomic_count.hpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // detail/atomic_count.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2022 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 ASIO_DETAIL_ATOMIC_COUNT_HPP
  11. #define 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 "asio/detail/config.hpp"
  16. #if !defined(ASIO_HAS_THREADS)
  17. // Nothing to include.
  18. #elif defined(ASIO_HAS_STD_ATOMIC)
  19. # include <atomic>
  20. #else // defined(ASIO_HAS_STD_ATOMIC)
  21. # include <boost/detail/atomic_count.hpp>
  22. #endif // defined(ASIO_HAS_STD_ATOMIC)
  23. namespace asio {
  24. namespace detail {
  25. #if !defined(ASIO_HAS_THREADS)
  26. typedef long atomic_count;
  27. inline void increment(atomic_count& a, long b) { a += b; }
  28. inline void decrement(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(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 decrement(atomic_count& a, long b) { a -= b; }
  35. inline void ref_count_up(atomic_count& a)
  36. {
  37. a.fetch_add(1, std::memory_order_relaxed);
  38. }
  39. inline bool ref_count_down(atomic_count& a)
  40. {
  41. if (a.fetch_sub(1, std::memory_order_release) == 1)
  42. {
  43. std::atomic_thread_fence(std::memory_order_acquire);
  44. return true;
  45. }
  46. return false;
  47. }
  48. #else // defined(ASIO_HAS_STD_ATOMIC)
  49. typedef boost::detail::atomic_count atomic_count;
  50. inline void increment(atomic_count& a, long b) { while (b > 0) ++a, --b; }
  51. inline void decrement(atomic_count& a, long b) { while (b > 0) --a, --b; }
  52. inline void ref_count_up(atomic_count& a) { ++a; }
  53. inline bool ref_count_down(atomic_count& a) { return --a == 0; }
  54. #endif // defined(ASIO_HAS_STD_ATOMIC)
  55. } // namespace detail
  56. } // namespace asio
  57. #endif // ASIO_DETAIL_ATOMIC_COUNT_HPP