atomic_count.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // detail/atomic_count.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2025 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. #else // !defined(BOOST_ASIO_HAS_THREADS)
  19. # include <atomic>
  20. #endif // !defined(BOOST_ASIO_HAS_THREADS)
  21. namespace boost {
  22. namespace asio {
  23. namespace detail {
  24. #if !defined(BOOST_ASIO_HAS_THREADS)
  25. typedef long atomic_count;
  26. inline void increment(atomic_count& a, long b) { a += b; }
  27. inline void decrement(atomic_count& a, long b) { a -= b; }
  28. inline void ref_count_up(atomic_count& a) { ++a; }
  29. inline bool ref_count_down(atomic_count& a) { return --a == 0; }
  30. inline void ref_count_up_release(atomic_count& a) { ++a; }
  31. inline long ref_count_read_acquire(atomic_count& a) { return a; }
  32. #else // !defined(BOOST_ASIO_HAS_THREADS)
  33. typedef std::atomic<long> atomic_count;
  34. inline void increment(atomic_count& a, long b) { a += b; }
  35. inline void decrement(atomic_count& a, long b) { a -= b; }
  36. inline void ref_count_up(atomic_count& a)
  37. {
  38. a.fetch_add(1, std::memory_order_relaxed);
  39. }
  40. inline bool ref_count_down(atomic_count& a)
  41. {
  42. if (a.fetch_sub(1, std::memory_order_release) == 1)
  43. {
  44. std::atomic_thread_fence(std::memory_order_acquire);
  45. return true;
  46. }
  47. return false;
  48. }
  49. inline void ref_count_up_release(atomic_count& a)
  50. {
  51. a.fetch_add(1, std::memory_order_release);
  52. }
  53. inline long ref_count_read_acquire(atomic_count& a)
  54. {
  55. return a.load(std::memory_order_acquire);
  56. }
  57. #endif // !defined(BOOST_ASIO_HAS_THREADS)
  58. } // namespace detail
  59. } // namespace asio
  60. } // namespace boost
  61. #endif // BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP