AtomicCounter.hpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 "NonCopyable.hpp"
  22. #ifndef __GNUC__
  23. #include <atomic>
  24. #endif
  25. namespace ZeroTier {
  26. /**
  27. * Simple atomic counter supporting increment and decrement
  28. */
  29. class AtomicCounter : NonCopyable
  30. {
  31. public:
  32. AtomicCounter()
  33. {
  34. _v = 0;
  35. }
  36. inline int operator++()
  37. {
  38. #ifdef __GNUC__
  39. return __sync_add_and_fetch(&_v,1);
  40. #else
  41. return ++_v;
  42. #endif
  43. }
  44. inline int operator--()
  45. {
  46. #ifdef __GNUC__
  47. return __sync_sub_and_fetch(&_v,1);
  48. #else
  49. return --_v;
  50. #endif
  51. }
  52. private:
  53. #ifdef __GNUC__
  54. int _v;
  55. #else
  56. std::atomic_int _v;
  57. #endif
  58. };
  59. } // namespace ZeroTier
  60. #endif