2013-07-04 20:56:19 +00:00
|
|
|
/*
|
2019-08-23 16:23:39 +00:00
|
|
|
* Copyright (c)2019 ZeroTier, Inc.
|
2013-07-04 20:56:19 +00:00
|
|
|
*
|
2019-08-23 16:23:39 +00:00
|
|
|
* Use of this software is governed by the Business Source License included
|
|
|
|
* in the LICENSE.TXT file in the project's root directory.
|
2013-07-04 20:56:19 +00:00
|
|
|
*
|
2019-08-23 16:23:39 +00:00
|
|
|
* Change Date: 2023-01-01
|
2013-07-04 20:56:19 +00:00
|
|
|
*
|
2019-08-23 16:23:39 +00:00
|
|
|
* On the date above, in accordance with the Business Source License, use
|
|
|
|
* of this software will be governed by version 2.0 of the Apache License.
|
2013-07-04 20:56:19 +00:00
|
|
|
*/
|
2019-08-23 16:23:39 +00:00
|
|
|
/****/
|
2013-07-04 20:56:19 +00:00
|
|
|
|
2013-12-07 00:49:20 +00:00
|
|
|
#ifndef ZT_ATOMICCOUNTER_HPP
|
|
|
|
#define ZT_ATOMICCOUNTER_HPP
|
2013-07-04 20:56:19 +00:00
|
|
|
|
2014-02-28 17:15:29 +00:00
|
|
|
#include "Constants.hpp"
|
2013-07-04 20:56:19 +00:00
|
|
|
|
2016-09-02 19:34:02 +00:00
|
|
|
#ifndef __GNUC__
|
2014-02-28 17:15:29 +00:00
|
|
|
#include <atomic>
|
|
|
|
#endif
|
|
|
|
|
2013-07-04 20:56:19 +00:00
|
|
|
namespace ZeroTier {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Simple atomic counter supporting increment and decrement
|
|
|
|
*/
|
2018-01-27 01:06:11 +00:00
|
|
|
class AtomicCounter
|
2013-07-04 20:56:19 +00:00
|
|
|
{
|
|
|
|
public:
|
2019-08-23 19:40:08 +00:00
|
|
|
ZT_ALWAYS_INLINE AtomicCounter() { _v = 0; }
|
2013-07-04 20:56:19 +00:00
|
|
|
|
2019-08-23 19:40:08 +00:00
|
|
|
ZT_ALWAYS_INLINE int load() const
|
2017-08-08 20:21:10 +00:00
|
|
|
{
|
|
|
|
#ifdef __GNUC__
|
2017-08-14 18:43:39 +00:00
|
|
|
return __sync_or_and_fetch(const_cast<int *>(&_v),0);
|
2017-08-08 20:21:10 +00:00
|
|
|
#else
|
|
|
|
return _v.load();
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
2019-08-23 19:40:08 +00:00
|
|
|
ZT_ALWAYS_INLINE int operator++()
|
2013-07-04 20:56:19 +00:00
|
|
|
{
|
|
|
|
#ifdef __GNUC__
|
|
|
|
return __sync_add_and_fetch(&_v,1);
|
2014-02-28 17:15:29 +00:00
|
|
|
#else
|
|
|
|
return ++_v;
|
2013-07-04 20:56:19 +00:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
2019-08-23 19:40:08 +00:00
|
|
|
ZT_ALWAYS_INLINE int operator--()
|
2013-07-04 20:56:19 +00:00
|
|
|
{
|
|
|
|
#ifdef __GNUC__
|
|
|
|
return __sync_sub_and_fetch(&_v,1);
|
2014-02-28 17:15:29 +00:00
|
|
|
#else
|
|
|
|
return --_v;
|
2013-07-04 20:56:19 +00:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2019-09-11 22:34:55 +00:00
|
|
|
ZT_ALWAYS_INLINE AtomicCounter(const AtomicCounter &) {}
|
|
|
|
ZT_ALWAYS_INLINE const AtomicCounter &operator=(const AtomicCounter &) { return *this; }
|
2018-01-27 01:06:11 +00:00
|
|
|
|
2016-09-02 19:34:02 +00:00
|
|
|
#ifdef __GNUC__
|
2013-07-04 20:56:19 +00:00
|
|
|
int _v;
|
2016-09-02 19:34:02 +00:00
|
|
|
#else
|
|
|
|
std::atomic_int _v;
|
2014-02-28 17:15:29 +00:00
|
|
|
#endif
|
2013-07-04 20:56:19 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace ZeroTier
|
|
|
|
|
|
|
|
#endif
|