AtomicCounter.hpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_ATOMICCOUNTER_HPP
  14. #define ZT_ATOMICCOUNTER_HPP
  15. #include "Constants.hpp"
  16. #ifndef __GNUC__
  17. #include <atomic>
  18. #endif
  19. namespace ZeroTier {
  20. /**
  21. * Simple atomic counter supporting increment and decrement
  22. */
  23. class AtomicCounter
  24. {
  25. public:
  26. AtomicCounter() { _v = 0; }
  27. inline int load() const
  28. {
  29. #ifdef __GNUC__
  30. return __sync_or_and_fetch(const_cast<int *>(&_v),0);
  31. #else
  32. return _v.load();
  33. #endif
  34. }
  35. inline int operator++()
  36. {
  37. #ifdef __GNUC__
  38. return __sync_add_and_fetch(&_v,1);
  39. #else
  40. return ++_v;
  41. #endif
  42. }
  43. inline int operator--()
  44. {
  45. #ifdef __GNUC__
  46. return __sync_sub_and_fetch(&_v,1);
  47. #else
  48. return --_v;
  49. #endif
  50. }
  51. private:
  52. AtomicCounter(const AtomicCounter &) {}
  53. const AtomicCounter &operator=(const AtomicCounter &) { return *this; }
  54. #ifdef __GNUC__
  55. int _v;
  56. #else
  57. std::atomic_int _v;
  58. #endif
  59. };
  60. } // namespace ZeroTier
  61. #endif