AtomicCounter.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. public:
  25. AtomicCounter()
  26. {
  27. _v = 0;
  28. }
  29. inline int load() const
  30. {
  31. #ifdef __GNUC__
  32. return __sync_or_and_fetch(const_cast<int*>(&_v), 0);
  33. #else
  34. return _v.load();
  35. #endif
  36. }
  37. inline int operator++()
  38. {
  39. #ifdef __GNUC__
  40. return __sync_add_and_fetch(&_v, 1);
  41. #else
  42. return ++_v;
  43. #endif
  44. }
  45. inline int operator--()
  46. {
  47. #ifdef __GNUC__
  48. return __sync_sub_and_fetch(&_v, 1);
  49. #else
  50. return --_v;
  51. #endif
  52. }
  53. private:
  54. AtomicCounter(const AtomicCounter&)
  55. {
  56. }
  57. const AtomicCounter& operator=(const AtomicCounter&)
  58. {
  59. return *this;
  60. }
  61. #ifdef __GNUC__
  62. int _v;
  63. #else
  64. std::atomic_int _v;
  65. #endif
  66. };
  67. } // namespace ZeroTier
  68. #endif