Created
December 14, 2018 09:11
-
-
Save wdanxna/a315fdb9ca2a33c25db1d6cb495b808f to your computer and use it in GitHub Desktop.
Thread safe Unique ID Generator in c++ using std::atomic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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