AtomicCounter.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_ATOMICCOUNTER_HPP
  19. #define ZT_ATOMICCOUNTER_HPP
  20. #include "Constants.hpp"
  21. #include "Mutex.hpp"
  22. #include "NonCopyable.hpp"
  23. #ifdef __WINDOWS__
  24. // <atomic> will replace this whole class eventually once it's ubiquitous
  25. #include <atomic>
  26. #endif
  27. namespace ZeroTier {
  28. /**
  29. * Simple atomic counter supporting increment and decrement
  30. */
  31. class AtomicCounter : NonCopyable
  32. {
  33. public:
  34. /**
  35. * Initialize counter at zero
  36. */
  37. AtomicCounter()
  38. throw()
  39. {
  40. _v = 0;
  41. }
  42. inline operator int() const
  43. throw()
  44. {
  45. #ifdef __GNUC__
  46. return __sync_or_and_fetch(const_cast <volatile int *>(&_v),0);
  47. #else
  48. #ifdef __WINDOWS__
  49. return (int)_v;
  50. #else
  51. _l.lock();
  52. int v = _v;
  53. _l.unlock();
  54. return v;
  55. #endif
  56. #endif
  57. }
  58. inline int operator++()
  59. throw()
  60. {
  61. #ifdef __GNUC__
  62. return __sync_add_and_fetch(&_v,1);
  63. #else
  64. #ifdef __WINDOWS__
  65. return ++_v;
  66. #else
  67. _l.lock();
  68. int v = ++_v;
  69. _l.unlock();
  70. return v;
  71. #endif
  72. #endif
  73. }
  74. inline int operator--()
  75. throw()
  76. {
  77. #ifdef __GNUC__
  78. return __sync_sub_and_fetch(&_v,1);
  79. #else
  80. #ifdef __WINDOWS__
  81. return --_v;
  82. #else
  83. _l.lock();
  84. int v = --_v;
  85. _l.unlock();
  86. return v;
  87. #endif
  88. #endif
  89. }
  90. private:
  91. #ifdef __WINDOWS__
  92. std::atomic_int _v;
  93. #else
  94. int _v;
  95. #ifndef __GNUC__
  96. #warning Neither __WINDOWS__ nor __GNUC__ so AtomicCounter using Mutex
  97. Mutex _l;
  98. #endif
  99. #endif
  100. };
  101. } // namespace ZeroTier
  102. #endif