2025-08-06 12:10:18 -04:00
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
2013-07-04 16:56:19 -04:00
|
|
|
*
|
2025-08-06 12:10:18 -04:00
|
|
|
* (c) ZeroTier, Inc.
|
|
|
|
|
* https://www.zerotier.com/
|
2013-07-04 16:56:19 -04:00
|
|
|
*/
|
|
|
|
|
|
2013-12-06 16:49:20 -08:00
|
|
|
#ifndef ZT_ATOMICCOUNTER_HPP
|
|
|
|
|
#define ZT_ATOMICCOUNTER_HPP
|
2013-07-04 16:56:19 -04:00
|
|
|
|
2016-09-02 12:34:02 -07:00
|
|
|
#ifndef __GNUC__
|
2014-02-28 09:15:29 -08:00
|
|
|
#include <atomic>
|
|
|
|
|
#endif
|
|
|
|
|
|
2013-07-04 16:56:19 -04:00
|
|
|
namespace ZeroTier {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Simple atomic counter supporting increment and decrement
|
|
|
|
|
*/
|
2025-07-03 11:26:23 -04:00
|
|
|
class AtomicCounter {
|
|
|
|
|
public:
|
|
|
|
|
AtomicCounter()
|
|
|
|
|
{
|
|
|
|
|
_v = 0;
|
|
|
|
|
}
|
2013-07-04 16:56:19 -04:00
|
|
|
|
2017-08-08 13:21:10 -07:00
|
|
|
inline int load() const
|
|
|
|
|
{
|
|
|
|
|
#ifdef __GNUC__
|
2025-07-03 11:26:23 -04:00
|
|
|
return __sync_or_and_fetch(const_cast<int*>(&_v), 0);
|
2017-08-08 13:21:10 -07:00
|
|
|
#else
|
|
|
|
|
return _v.load();
|
|
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
2013-07-04 16:56:19 -04:00
|
|
|
inline int operator++()
|
|
|
|
|
{
|
|
|
|
|
#ifdef __GNUC__
|
2025-07-03 11:26:23 -04:00
|
|
|
return __sync_add_and_fetch(&_v, 1);
|
2014-02-28 09:15:29 -08:00
|
|
|
#else
|
|
|
|
|
return ++_v;
|
2013-07-04 16:56:19 -04:00
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
inline int operator--()
|
|
|
|
|
{
|
|
|
|
|
#ifdef __GNUC__
|
2025-07-03 11:26:23 -04:00
|
|
|
return __sync_sub_and_fetch(&_v, 1);
|
2014-02-28 09:15:29 -08:00
|
|
|
#else
|
|
|
|
|
return --_v;
|
2013-07-04 16:56:19 -04:00
|
|
|
#endif
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-03 11:26:23 -04:00
|
|
|
private:
|
|
|
|
|
AtomicCounter(const AtomicCounter&)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
const AtomicCounter& operator=(const AtomicCounter&)
|
|
|
|
|
{
|
|
|
|
|
return *this;
|
|
|
|
|
}
|
2018-01-26 20:06:11 -05:00
|
|
|
|
2016-09-02 12:34:02 -07:00
|
|
|
#ifdef __GNUC__
|
2013-07-04 16:56:19 -04:00
|
|
|
int _v;
|
2016-09-02 12:34:02 -07:00
|
|
|
#else
|
|
|
|
|
std::atomic_int _v;
|
2014-02-28 09:15:29 -08:00
|
|
|
#endif
|
2013-07-04 16:56:19 -04:00
|
|
|
};
|
|
|
|
|
|
2025-07-03 11:26:23 -04:00
|
|
|
} // namespace ZeroTier
|
2013-07-04 16:56:19 -04:00
|
|
|
|
|
|
|
|
#endif
|