Skip to content

Instantly share code, notes, and snippets.

@wdanxna
Created December 14, 2018 09:11
Show Gist options
  • Save wdanxna/a315fdb9ca2a33c25db1d6cb495b808f to your computer and use it in GitHub Desktop.
Save wdanxna/a315fdb9ca2a33c25db1d6cb495b808f 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