atomic_count.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // detail/atomic_count.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 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. #else // !defined(BOOST_ASIO_HAS_THREADS)
  31. typedef std::atomic<long> atomic_count;
  32. inline void increment(atomic_count& a, long b) { a += b; }
  33. inline void decrement(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. #endif // !defined(BOOST_ASIO_HAS_THREADS)
  48. } // namespace detail
  49. } // namespace asio
  50. } // namespace boost
  51. #endif // BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP