2015-12-08 04:51:55 +08:00
|
|
|
#pragma once
|
2015-07-31 18:35:14 +08:00
|
|
|
|
|
|
|
#include <atomic>
|
2015-09-13 18:56:30 +08:00
|
|
|
#include <type_traits>
|
2015-07-31 18:35:14 +08:00
|
|
|
|
2015-09-13 18:56:30 +08:00
|
|
|
template <class T,
|
|
|
|
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
|
2015-07-31 18:35:14 +08:00
|
|
|
class AtomicCounter
|
|
|
|
{
|
|
|
|
public:
|
2015-09-13 18:56:30 +08:00
|
|
|
AtomicCounter(T initial = 0) : counter(initial) {}
|
2015-07-31 18:35:14 +08:00
|
|
|
|
2015-09-13 18:56:30 +08:00
|
|
|
T next(std::memory_order order = std::memory_order_seq_cst)
|
2015-07-31 18:35:14 +08:00
|
|
|
{
|
2015-09-13 18:56:30 +08:00
|
|
|
return counter.fetch_add(1, order);
|
|
|
|
}
|
|
|
|
|
|
|
|
T operator++()
|
|
|
|
{
|
|
|
|
return next();
|
2015-07-31 18:35:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::atomic<T> counter;
|
|
|
|
};
|