AtomicCounter.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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. #include "NonCopyable.hpp"
  30. #ifndef __GNUC__
  31. #include <atomic>
  32. #endif
  33. namespace ZeroTier {
  34. /**
  35. * Simple atomic counter supporting increment and decrement
  36. */
  37. class AtomicCounter : NonCopyable
  38. {
  39. public:
  40. AtomicCounter()
  41. {
  42. _v = 0;
  43. }
  44. inline int load() const
  45. {
  46. #ifdef __GNUC__
  47. return __sync_or_and_fetch(const_cast<int *>(&_v),0);
  48. #else
  49. return _v.load();
  50. #endif
  51. }
  52. inline int operator++()
  53. {
  54. #ifdef __GNUC__
  55. return __sync_add_and_fetch(&_v,1);
  56. #else
  57. return ++_v;
  58. #endif
  59. }
  60. inline int operator--()
  61. {
  62. #ifdef __GNUC__
  63. return __sync_sub_and_fetch(&_v,1);
  64. #else
  65. return --_v;
  66. #endif
  67. }
  68. private:
  69. #ifdef __GNUC__
  70. int _v;
  71. #else
  72. std::atomic_int _v;
  73. #endif
  74. };
  75. } // namespace ZeroTier
  76. #endif