AtomicCounter.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_ATOMICCOUNTER_HPP
  27. #define ZT_ATOMICCOUNTER_HPP
  28. #include "Constants.hpp"
  29. #ifndef __GNUC__
  30. #include <atomic>
  31. #endif
  32. namespace ZeroTier {
  33. /**
  34. * Simple atomic counter supporting increment and decrement
  35. */
  36. class AtomicCounter
  37. {
  38. public:
  39. AtomicCounter() { _v = 0; }
  40. inline int load() const
  41. {
  42. #ifdef __GNUC__
  43. return __sync_or_and_fetch(const_cast<int *>(&_v),0);
  44. #else
  45. return _v.load();
  46. #endif
  47. }
  48. inline int operator++()
  49. {
  50. #ifdef __GNUC__
  51. return __sync_add_and_fetch(&_v,1);
  52. #else
  53. return ++_v;
  54. #endif
  55. }
  56. inline int operator--()
  57. {
  58. #ifdef __GNUC__
  59. return __sync_sub_and_fetch(&_v,1);
  60. #else
  61. return --_v;
  62. #endif
  63. }
  64. private:
  65. AtomicCounter(const AtomicCounter &) {}
  66. const AtomicCounter &operator=(const AtomicCounter &) { return *this; }
  67. #ifdef __GNUC__
  68. int _v;
  69. #else
  70. std::atomic_int _v;
  71. #endif
  72. };
  73. } // namespace ZeroTier
  74. #endif