Skip to content

Instantly share code, notes, and snippets.

@WanpengQian
Forked from wdanxna/UniqueIDGenerator.cpp
Created March 19, 2021 06:49
Show Gist options
  • Save WanpengQian/7e4ef385d354f25e89e95f0b366036e6 to your computer and use it in GitHub Desktop.
Save WanpengQian/7e4ef385d354f25e89e95f0b366036e6 to your computer and use it in GitHub Desktop.
Thread safe Unique ID Generator in c++ using std::atomic
template <typename T>
struct UniqueIDGenerator {
std::atomic<T> _id;
std::function<const T(const T&)> _nexter;
template <typename NEXT>
UniqueIDGenerator(const T& init, const NEXT& nexter) {
_id.store(init, std::memory_order::memory_order_release);
_nexter = nexter;
}
const T fetch_add() {
T oldVal;
T newVal;
do {
oldVal = _id;
newVal = _nexter(oldVal);
} while (!_id.compare_exchange_weak(oldVal, newVal));
return oldVal;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment